I have an array and I want to overwrite all values in it (that are all numbers) with a 0. So the array already exists.
I can do this with a for loop. However, is there a fill() call of some kind like the Java Arrays.fill()?
A very simple for-loop is all you need. There's no fill-function in JavaScript.
var length = arr.length,
for (var i = 0; i < length; i++) {
arr[i] = 0;
}
You can use map for this.
var arr = [1,2,3];
arr = arr.map(function() {return 0});
//arr = [0, 0, 0]
The performance may be worse than a plain for loop.
Related
Looking for a resource to explain why when I run the below code, my original array doesn't change.
arr = [1,2,3,4];
for(let val of arr){
val = val * 2;
console.log(val);
}
console.log(arr);
I am learning about for...in and for...of loops and not sure why my console.log(arr) doesn't print out [2,4,6,8].
The problem here is that the the identifier val is being overwritten. With another integer and val is just a temp variable invoked each iteration of the loop. If you used an object, and did not reassign the variable, your values would remain intact
// Object values
var x = [{z:1},{z:2}]
for(let y of x){
// No reassignment
y.z=3;
}
console.log(x); //[{"z":3},{"z":3}]
If you want to modify an array of simple types in place, you can do something like:
var q = [5,6,7];
for( i in q){
q[i] = q[i] * 2;
}
console.log(q); //[10, 12, 14]
Use a for loop, which enables you to make the assignments "stick" in the original array.
arr = [1,2,3,4];
for (var i=0; i < arr.length; i++) {
arr[i] = 2*arr[i];
console.log(arr[i]);
}
The issue with what you were originally doing is that val is just a variable with no real connection to the underlying array. Hence, doubling val has no effect on the array itself.
You are modifying and not inserting in back.
Better you use for each this case. So that you'll be able to modify the array. Using of make things complicated.
arr = [1,2,3,4];
arr.forEach(function(part, index, array) {
array[index] = array[index]*2;
});
console.log(arr);
You can achieve this using forEach too, which runs a particular function for every value in the array.
arr = [1,2,3,4];
arr.forEach((d, i, arr) => arr[i]*=2);
console.log(arr);
Just wondering, what is the most efficient way to divide an array by a scalar? I can clearly loop over it, but efficiency is paramount in my case.
Common trivial way:
var array_2 = []
var array_1 = [original_data
var divisor = my_scalar
for(var i = 0, length = array.length; i < length; i++){
array_2.push(array[i]/divisor)
}
Any trick I can use (or a new approach altogether)?
You've said you want the most efficient way. Fairly sure what you're doing is close, but you want assignment rather than push, and in at least some JavaScript engines (V8 for instance, in the Chromium browsers), if you tell the Array constructor an initial length, they'll pre-allocate backing storage (even though the array starts with no elements in it):
var array_2 = Array(array.length);
for(var i = 0, length = array.length; i < length; i++){
array_2[i] = array[i] / divisor;
}
Having said that: The difference between that and map is going to be very very very very very very small and it's an exceptionally rare use case where it would matter. Whereas map is clear, simple, short...
const numbers = [350,451,758,456,999];
const dividedNum = num => num/7;
const output1 = numbers.map(dividedNum);
console.log(output1)
You could use map for that:
var newData = data.map(function(item) { return item/scalar } )
Is there a faster way to create and zero out a matrix?
Currently, my code involves two for loops:
var nodes = new Array(ast.length);
for (var i=0; i < nodes.length; i++){
nodes[i] = new Array(ast.length);
for (var j=0; j < nodes.length; j++)
nodes[i][j]=0;
}
You could use the Array.prototype.fill method:
var nodes = Array(ast.length).fill(Array(ast.length).fill(0));
jsperf test: http://jsperf.com/fill-array-matrix
Since you asked for "faster", it looks like you can gain some speed by creating a single initalized array and then using .slice() to copy it rather than initializing each array itself:
var nodes = new Array(ast.length);
var copy = new Array(ast.length);
for (var i = 0; i < ast.length; i++) {
copy[i] = 0;
}
for (var i=0; i < nodes.length; i++){
nodes[i] = copy.slice(0);
}
jsperf test: http://jsperf.com/slice-vs-for-two-d-array/2
This method looks to be 10-20% faster in all three major browsers.
You can create array of zeros once and create copies of it:
var length = 10;
var zeros = Array.apply(null, Array(length)).map(Number.prototype.valueOf, 0);
var nodes = zeros.map(function(i) {
return zeros.slice();
});
console.log(nodes);
I don't know how fast this is in terms of producing a 2d array but it is IMHO a better way that most.
Array.prototype.dim = function(){
if( this.length==2 ){
r=this.shift(); c=this.shift();
while( r-- ) this.push( new Array( c ).fill(0,0) );
return this;
}
}
In use, the 2d array is made by initialising a regular 1d array with the parameters of x,y or rows, cols as two parameters. These are then used to dimension the array and fill it with zeros at the same time.
var arr = new Array(5,7).dim();
console.log(arr[4]);
The array then has got the desired dimension with zeros.
The output:
console.log(arr[4]);
(7) [0, 0, 0, 0, 0, 0, 0]
I hope someone finds this useful.
I am trying to make a removeAll() function, which will remove all elements of an array with that particular value (not index).
The tricky part comes when we make any change to the loop, the indexes tend to move around (making it very hard to make it work like we want) and, restarting the loop every time we make changes is very inefficient on big arrays.
So far, I wrote my own arr.indexOf function (for older IE support), it looks like this:
function arrFind(val, arr) {
for (var i = 0, len = arr.length, rtn = -1; i < len; i++) {
if (arr[i] === val) {
return i;
}
}
return -1;
}
It is easy to remove elements like this:
var myarray = [0, 1, 2, 3, 4];
var tofind = 2;
var stored_index = arrFind(tofind, myarray);
if (stored_index != -1) {
myarray.splice(stored_index, 1);
}
alert(myarray.join(",")); //0,1,3,4
However, as I pointed out earlier, when doing this while looping, we get in trouble.
Any ideas on how to properly remove array items while looping through it?
Loop in reverse order or build a new array with the items that are not to be removed.
Every new browser has an Array filter method:
var myarray=[0,1,2,3,4];
var removal=2;
var newarray=myarray.filter(function(itm){return itm!==removal});
Try this one. You just have to check the indices of the numbers you would like to remove. I have added additional elements in your array.
var myarray = [0, 1, 2, 3, 2, 2, 2, 5, 6];
var indicesToRemove = new Array();
for(i=0;i<myarray.length;i++){
if(myarray[i]===2){ //let's say u wud like to remove all 2
indicesToRemove.push(i); //getting the indices and pushing it in a new array
}
}
for (var j = indicesToRemove.length -1; j >= 0; j--){
myarray.splice(indicesToRemove[j],1);
}
alert(JSON.stringify(myarray)); //myarray will be [0,1,3,5,6]
I wrote this little function where arr is the original array and d1, d2 the values you want removed. I wonder how it could be generalized to an arbitrary number of values to be removed. Well, I'm just a beginner.
function destroyer(arr, d1, d2) {
var lean =[];
for (var i = 0; i<arr.length; i++) {
if (arr[i] != d1 && arr[i] != d2) {
lean.push(arr[i]);
}
}
return lean;
I have the length of my previous object and i need to create a new array of objects based on the length with new key's.
Length = 3;
var newArray = [];
for(var i =0; i <3; i++){
var Object = {};
Object['newKey'] = 1;
newArray.push(Object);
}
This would eventually create newArray of Objects whose length is 3 containing something like this.. newArray[0],[1],[2].
Am i doing this correctly, please do suggest me if anything wrong or a better way to do this.
Here's what you wrote (I think), just shortened a bit (and fixed the capitalization of variable names)
var length = 3;
var newArray = [];
for( var i = 0 ; i < length ; i++ ) {
newArray.push({newKey: 1});
}
but to be honest it's unclear to me exactly what you're trying to accomplish
You could make it slightly more dynamic by referencing the variable for length.
Example updated per comments:
var length = 3,
newArray = [];
for ( var i=0; i<length; i++ ) {
var tempObj = {};
tempObj['newKey'] = 'SomeValue';
newArray.push(tempObj);
}
I didn't really do more than clean up what you have.