How to push multiple zeros to an already existing array - javascript

I found on this link how to create arrays with a chosen number of zeros.
Most efficient way to create a zero filled JavaScript array?
But my question is, imagine i already have a array
var a = ['hihi','haha']
how can i add 12 zeros after my two first elements ? So that it becomes :
a = ['hihi','haha',0,0,0,0,0,0,0,0,0,0,0,0];
of course I could go for a
for(var i = 0; i < 12, i++){
a.push(0);
}
but is there a one line method ? something like
a.push(6*[0]);

You can use Array.prototype.concat() and Array.prototype.fill()
Create an array with size 12 and fill 0 by using Array.prototype.fill()
Then concatenate with existing array using Array.prototype.concat()
var a = ['hihi', 'haha'].concat(Array(12).fill(0));
document.write('<pre>' + JSON.stringify(a, null, 3) + '</pre>');

You could for instance use a solution from the answer you link to create an array of twelve zeroes, and then use the Array.prototype.concat function to create the array you need.
var zeroes = Array.apply(null, Array(12)).map(Number.prototype.valueOf, 0);
var laughters = ['hihi', 'haha'];
var combined = laughters.concat(zeroes);

function fillArray(value, len) {
if (len == 0) return [];
var a = [value];
while (a.length * 2 <= len) a = a.concat(a);
if (a.length < len) a = a.concat(a.slice(0, len - a.length));
return a;
}
It doubles the array in each iteration, so it can create a really large array with few iterations.

In short, take your array and perform a concat with the answer you mentioned.
var a = ['hihi','haha'].concat(Array.apply(null, Array(12)).map(Number.prototype.valueOf,0);)

Must de 0 be an int or a string?
And why do you want to add 12 zeros?
What do you have tried so far?
Just an easy sample,
var a = ['hi', 'ha'];
for(var i = 0; 14 > a.length; i++){
a.push(0);
}

Related

Combine an array with other arrays, push each combination Javascript

I'm trying to take an array, and compare each value of that array to the next value in the array. When I run my code, components that should match with more than one array only return one match, instead of all of them. I'm probably doing something wrong somewhere, but for the life of my I don't seem to be able to figure it out.
This is my code:
INPUT
minterms = [["4",[0,1,0,0]],
["8",[1,0,0,0]],
["9",[1,0,0,1]],
["10",[1,0,1,0]],
["12",[1,1,0,0]],
["11",[1,0,1,1]],
["14",[1,1,1,0]],
["15",[1,1,1,1]]];
Function
function combineMinterms(minterms) {
var match = 0;
var count;
var loc;
var newMin = [];
var newMiny = [];
var used = new Array(minterms.length);
//First Component
for (x = 0; x < minterms.length; x++) {
if(minterms[x][1][minterms[x][1].length - 1] == "*") {
newMin.push(minterms[x].slice());
continue;
};
//Second Component
for (y = x + 1; y < minterms.length; y++) {
count = 0;
//Compare each value
for (h = 0; h < minterms[x][1].length; h++) {
if (minterms[x][1][h] != minterms[y][1][h]) {
count++;
loc = h;
}
if (count >= 2) {break; };
}
//If only one difference, push to new
if (count === 1) {
newMin.push(minterms[x].slice());
newMiny = minterms[y].slice();
newMin[match][1][loc] = "-";
while(newMin[match][0].charAt(0) === 'd') {
newMin[match][0] = newMin[match][0].substr(1);
}
while(newMiny[0].charAt(0) === 'd') {
newMiny[0] = newMiny[0].substr(1);
}
newMin[match][0] += "," + newMiny[0];
used[x] = 1;
used[y] = 1;
match++;
continue;
}
}
//If never used, push to new
if(used[x] != 1) {
newMin.push(minterms[x].slice());
newMin[match][1].push("*");
match++;
}
}
return newMin;
}
Desired Output
newMin = [["4,12",[-,1,0,0]],
["8,9",[1,0,0,-]],
["8,10",[1,0,-,0]],
["8,12",[1,-,0,0]],
["9,11",[1,0,-,1]],
["10,11",[1,0,1,-]],
["10,14",[1,-,1,0]],
["12,14",[1,1,-,0]],
["11,15",[1,-,1,1]],
["14,15",[1,1,1,-]]];
It will combine term 8, with 9 but won't continue to combine term 8 with 10, 12
Thanks in advance for the help.
Array.prototype.slice performs a shallow copy.
Each entry in minterms is an array of a string and a nested array.
When you slice the entry, you get a new array with a copy of the string and a copy of the Array object reference. But that copy of the Array reference still points to the array contained in an element of minterms.
When you update the nested array
newMin[match][1][loc] = "-";
you are updating the nested array within the input. I never fathomed the logic of what you are doing, but I believe this is the problem, with solution of cloning the nested array (as well) when cloning an input array element.
A secondary issue you will probably wish to fix is that not all variables were declared: var x,y,h; or equivalent inline declarations are missing.
let minterms = [4,8,9,10,12,11,14,15];
let newMin = [];
minterms.map((value, index) =>{
minterms.reduce((accumulator, currentValue, currentIndex, array) => {
accumulator = value;
let out = (accumulator ^ currentValue).toString(2);
if(out.split('').filter(n=>n==="1").length == 1) newMin.push([value, currentValue]);
}, value);
});
console.log(newMin);
There is a better approach (in 10 lines of code). Since you're working with binary representations, you might want to consider using BitWise operators. When coupled with array operators it makes most of this straight forward.
For instance:
Given a match means only a single bit differs between two binary numbers:
The bitwise XOR operator returns 1 for each bit that doesn't match. So:
0100 XOR 1000 results in 1000
Now, we need to count the number of '1' digits in the binary number returned. We can use the length property of an array to do this. To turn 1000 into an array, first we turn the binary into a string:
The binary representation of the integer 4 is easily retrieved with:
num.toString(2)
So if num === 4, the output above is the string "0100".
Now we use str.split() to turn the string into an array. Remove everything from the array that is not a '1'. Now simply get the length property. If the length === 1, it is a match.
I put together a solution like this for you. It is close to your use case. I didn't use the funny dash style in the output because that was not part of your question.
https://jsbin.com/xezuwax/edit?js,console

Eliminate duplicate values javascript

I try to draw a graph from tens of thousands points, but because this number is so big i need to reduce it. Many of them have duplicates. I tried to reduce the number using this:
var array=_.reject(data,function(object,i){
return i>0 && (data[i-1].a === object.a && data[i-1].b===object.b && data[i-1].c===object.c);
});
How can i modify this function, or to create a new one, in order to keep first and last value considered duplicate. Those are different by another attribute 'd' which represent a time stamp.
//return filtered points, compareFunction for sorting, equalFunction for
//removing points
function removeDuplicate(data,compareFunction,equalFunction) {
data.sort(function(pointa, pointb) {
var compare = compareFunction(pointa,pointb);
return compare;
});
var arr = new Array();
var prev = new Object();
var index = 0;
for (var i = 0; i < data.length; i++) {
if (i == 0 || !(equalFunction(prev,data[i]))) {
arr[index++] = data[i];
prev = data[i];
}
}
return arr;
}
function compareFunction(pointa,pointb){
return (pointa.a + pointa.b + pointa.c) - (pointb.a + pointb.b + pointb.c);
}
function equalFunction(pointa,pointb){
return pointa.a == pointb.a && pointa.b == pointb.b && pointa.c == pointb.c;
}
example - https://jsfiddle.net/8xu4Lwp2/
The simplest way to eliminate duplicates from an array in JavaScript is to cast it as a Set and then back to an Array. Sets don't store duplicates.
// not sure why setArr isn't logging, it does in Opera console.
arr=[1,1,2,2,3,3];
console.log(arr);
setArr=new Set(arr);
console.log(setArr);
newArr=[...setArr];
console.log(newArr);
Cool solution:
var unique = Array.from(new Set(arrayWithDuplicatedValue));

Find maximum variable using JavaScript

I have thirty variables which are all numbers:
h0 = 23
h1 = 27
h2 = 90
...
How do I find the largest variable?
The output here should be h2.
Assuming the variables are all named in consecutive order, you can add them to an array:
var values = [h0, h1, ....h29];
Then iterate over the array, compare the values and keep track of the index of the max value:
var maxIndex = 0;
for (var i = 1; i < values.length; i++) {
if (values[maxIndex] < values[i]) {
maxIndex = i;
}
}
maxIndex will now contain the index of the maximum value, and you could concat it with 'h', e.g.
console.log('h' + maxIndex);
Of course this approach makes a lot of assumptions and is fragile, but that's what you get when doing this kind of "meta-programming" (the variable name really should not be of any concern to anybody using the app).
Using an object would make it a bit better, at least concerning the variable name:
var values = {
h0: h0,
h1: h1,
...
};
var maxProp = '';
for (var prop in values) {
if (values[maxProp] < values[prop]) {
maxProp = prop;
}
}
Put them in an array instead of individual variables, then loop over the array.
To brute-force it, compare adjacent pairs of variables, then pairs of the results, until only one is left.
If you want the answer to be 'h2' instead of '90' (per comment), try using an Object instead of separate variables (or an array, as mentioned in other answers).
var find_max = {
'h0': 23,
'h1': 27,
'h2': 90,
// and so on
};
Then loop over the properties of the object to find the maximum.
var max;
for (var h in find_max) {
if (!max || (find_max[h] > find_max[max])) {
max = h;
}
}
You can probably improve this loop - try using hasOwnProperty to make sure that the only items in the loop are the ones you want.
You can get it easily by checking the window object using the bracket notation this way:
h0 = 11;
h1 = 24;
h2 = 28;
h3 = 345;
h4 = 1;
var i = 0;
var max = {
name: 'none',
val: 0
};
while (nextItem = window['h'+i]) {
if (nextItem > max.val) {
max = {
name: 'h'+i,
val: nextItem
};
};
i++;
};
document.getElementById('max').innerHTML = max.name + ' = ' + max.val;
<p>Maximum is: <span id="max"></span></p>
EDIT: I was too hasty in posting the below as it didn't take into account the real question. Since then there have been good answers presented so I'll just show a way that you can sort the variables in descending order. One way would be to place the numbers in an array of objects such that:
numArray = [{name:h0, value:23}, {name:h1, value:27}, {name:h2, value:90}];
And do:
numArray.sort(function(a, b){
return b.value - a.value;
});
According to this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
It looks pretty easy once you have the numbers in an array. You could call
Math.max.apply(null, numArray)
on the array, or, using ES6, you could say Math.max(...numArray) (... is the "spread" operator).
You could also do a sort:
numArray.sort(function(a, b){
return b - a;
});
Which would sort your array in descending order with the maximum number now at numArray[0].

Splitting a number into an array

Alright so I'm trying to completely split a number into an Array. So for example:
var num = 55534;
var arr = []; <- I would want the Array to look like this [5,5,5,3,4]
Basically i want to to completely split the number apart and place each Number into its own element of the array. Usually in the past i would just convert the number into a string then use the .split() function. This is how i use to do it:
num += "";
var arr = num.split("");
But this time i actually need to use these numbers, so they can not be strings. What would you guys say be the way of doing this?
Update, after the edit for some reason my code is crashing every run:
function DashInsert(num) {
num += "";
var arr = num.split("").map(Number); // [9,9,9,4,6]
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 === 1){
arr.splice(i,0,"-");
}// odd
}
return arr.join("");
}
String(55534).split("").map(Number)
...will handily do your trick.
You can do what you already did, and map a number back:
55534..toString().split('').map(Number)
//^ [5,5,5,3,4]
I'll do it like bellow
var num = 55534;
var arr = num.toString().split(''); //convert string to number & split by ''
var digits = arr.map(function(el){return +el}) //convert each digit to numbers
console.log(digits); //prints [5, 5, 5, 3, 4]
Basically I'm converting each string into numbers, you can just pass Number function into map also.

how to make string as array in java script?

I have a string value like:
1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i
I need to convert it into array in JavaScript like
1 2 3
4 5 6
7 8 9
etc.
Can any one please suggest me a way how to do this?
You are looking for String.split. In your case, you need to split twice. Once with ; to split the string into chunks, then separately split each chunk with , to reach the array structure you are looking for.
function chunkSplit(str) {
var chunks = str.split(';'), // split str on ';'
nChunks = chunks.length,
n = 0;
for (; n < nChunks; ++n) {
chunks[n] = chunks[n].split(','); // split each chunk with ','
}
return chunks;
}
var arr = chunkSplit("1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i");
If you need a multi-dimensional array you can try :
var array = yourString.split(';');
var arrCount = array.length;
for (var i = 0; i < arrCount; i++)
{
array[i] = array[i].split(',');
}
Try the following:
var yourString = '1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var array = [];
yourString.split(';').forEach(function(value) {
array.push(value.split(','));
});
jsFiddle Demo
Note: .forEach() not supported in IE <=8
The following split command should help:
yourArray = yourString.split(";");

Categories

Resources