Array with numbers 1-20 [duplicate] - javascript

This question already has answers here:
How to create an array containing 1...N
(77 answers)
Closed 9 years ago.
I'm brand new to javascript. I was working through a problem earlier where I needed an array that included the numbers 1 thru 20.
I did this with the following:
var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
QUESTION:
I can't help but think that this is not efficient (and certainly not scalable). Is there a way to create an array that automatically populates with sequential values between 1 and 20, or 1 and 1000 for instance?

Here's a oneliner:
var myArr = Array(20).join().split(',').map(function(a){return this.i++},{i:1});
or a tiny bit shorter:
var myArr = (''+Array(20)).split(',').map(function(){return this[0]++;}, [1]);
Both methods create an empty Array with 20 empty elements (i.e. elements with value undefined). On a thus created Array the map method can't be applied 1, so the join (or string addition) and split trick transforms it to an Array that knows it. Now the map callback (see the MDN link) does nothing more than sending an increment of the initial value ({i:1} or [1]) back for each element of the Array, and after that, myArr contains 20 numeric values from 1 to 20.
Addendum: ES20xx
[...Array(21).keys()].slice(1);
Array.map => See also...
See also this Stackblitz project.
1 Why not? See this SO answer, and this one for a more profound explanation

You could use a simple loop to do what you want;
var numberArray = [];
for(var i = 1; i <= 20; i++){
numberArray.push(i);
}
console.log(numberArray);

Related

Finding last occurences of element in Array of Array with lastIndexOf [duplicate]

This question already has answers here:
Find last index of element inside array by certain condition
(23 answers)
Closed 2 years ago.
Is it possible somehow to use the lastIndexOf method to get the value of a variable in an array of array? For example if I had
[[1,2,3,4],[4,6,4,7,5], [5,7,4,6,3], [6,2,5,4,3]]
and I wanted to find the index of the last array where [1] was 2? In the above I would expect the answer to be 3 as the third array has [1] equal to 2.
I can see how I can make this work with nested loops or array methods but just wondered if there's some syntax I'm not aware of. Cheers
No.
Because Array.prototype.lastIndexOf() only accepts an element, and not a callback, you can't use lastIndexOf() for this case directly.
Given this, and that there's no standard findLastIndex() prototype function, you'll have to write this functionality yourself. Here's one such way, using reduce() and findIndex(), while avoiding mutating the original array:
const arr = [[1,2,3,4],[4,6,4,7,5], [5,7,4,6,3], [6,2,5,4,3]];
function findLastIndex(arr, callback) {
return (arr.length - 1) - // Need to subtract found, backwards index from length
arr.slice().reverse() // Get reversed copy of array
.findIndex(callback); // Find element satisfying callback in rev. array
}
console.log(findLastIndex(arr, (e) => e[1] == 2));
I discovered arr.slice().reverse() from this answer by user #Rajesh, which is much faster than my previous reducer.

Javascript: Subarrays contain reference to other arrays even though parent is its own array? [duplicate]

This question already has answers here:
How do you clone an array of objects in JavaScript?
(40 answers)
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 4 years ago.
OK.
Let me try to say this in some sort of comprehensible manner. I'm an amateur programmer writing my own take on a neural network in javascript. (Without having seen the code for a neural network before)
I was having problems with an array changing when I was trying to change a copy of the array. (Not the original)
I soon realized after rereading what I'd written that when you assign an identifier to an array it doesn't make the identifier a new object with a copy of the array. Instead, it makes a reference to the original array object, for example:
var arr = [1,2,3];
var arr2 = arr;
arr2[0] = 9;
alert(arr);
//Alerts "9,2,3"
With this mind, I googled and found a quick solution:
var arr = [1,2,3];
var arr2 = arr.slice();
arr2[0] = 9;
alert(arr);
//Alerts "1,2,3"
So I changed this in my actual project expecting to see my work completed, but no! I was getting the exact results as before where my array was changing even though it was not supposed to.
After much effort at debugging, I finally worked out that the problem here is that I have a large array of subarrays, which in turn have subarrays.
In code this looks like:
var arr = [
[[1],[2]],
[[4],[5]],
[[7],[8]]
];
As you can see, there is one big array that contains 3 smaller arrays, each of which contains two even smaller arrays, each of which contains a number.
In my project, it's more complicated than this and has a couple more layers but this is a decent representation.
So what did I expect to happen?
var arr = [
[[1],[2]],
[[4],[5]],
[[7],[8]]
];
var other = arr.slice();
other[0][0][0] = "Uh Oh";
alert(arr);
//Outputs "1,2,3,4,5,6,7,8"
What actually happened?
alert(arr);
//Outputs "Uh Oh,2,3,4,5,6,7,8"
Why does this happen?
How can I fix it?
Thanks in advance.
Try following
var arr = [
[[1],[2]],
[[4],[5]],
[[7],[8]]
];
var other = JSON.parse(JSON.stringify(arr));
other[0][0][0] = "Uh Oh";
console.log(arr);
Reasoning
arr.slice() creates different reference for the array, however, any child object/array will still continue to hold the same reference. But you need to change the references of the child object/array as well, for that convert it into a string and then back to object - It will create different references for all the objects.

Do undefined elements in an array have an impact in JS? [duplicate]

This question already has answers here:
Deleting array elements in JavaScript - delete vs splice
(29 answers)
Closed 4 years ago.
I couldn't find a question that specifically targets the issue I'm having hence this question is being asked.
I have an array that holds 5 numbers:
var numbers = [0,1,2,3,4];
Once a number is clicked on the frontend (website), the number is removed from the array using the below code:
delete numbers[1];
This removes the correct number but leaves a space where the number was (the space is undefined). I believe this is causing an issue. After a number is removed from the array, I use another function to randomly pick any of the remaining numbers in the array however it sometimes fails. After much thought, I've realized it may be because there are empty spaces in the array after a number is removed and as a result, the code fails to work due to the undefined element.
Is my analogy correct or am I mistaken?
(I have also attempted to use the splice method to remove the number however that then causes an issue with the length of my array because if I later want to remove another number, it removes the wrong one due to the numbers moving around etc).
What you'd want to use is splice
In your specific case, numbers.splice(1,1)
You're correct that delete replaces one of the values in the array with undefined, and does not change the array length. Later on when you randomly choose an element from the array, you can wind up getting that undefined value, because it's still taking up a slot in the array:
var numbers = [0,1,2,3,4];
delete numbers[3];
console.log(numbers)
Instead use splice, which removes the item from the array completely:
var numbers = [0,1,2,3,4];
numbers.splice(3,1) /// remove one element starting at index 3
console.log(numbers)
if I later want to remove another number, it removes the wrong one due to the numbers moving around
You do need to choose one behavior or the other. If you need to preserve indexes as is, then continue to use delete, leaving the undefined values in the array, and rewrite your "choose one at random" function to never pick undefined values:
// start with some undefined values:
var numbers = [0, 1, undefined, undefined, undefined, 5]
var pickRandom = function(numbers) {
// make a copy of the array, removing undefined elements:
var definedValues = numbers.filter(function(item) {
return item !== undefined;
});
if (definedValues.length === 0) {return false}
//choose one at random:
return definedValues[Math.floor(Math.random() * definedValues.length)]
}
// test it:
console.log(pickRandom(numbers));
console.log(pickRandom(numbers));
console.log(pickRandom(numbers));
console.log(pickRandom(numbers));
(...but note that this suggests that a simple array is the wrong data structure to use here; you may be better off with an array of objects each with an explicit ID, so you can reference specific ones as needed without worrying about keeping the array index the same.)
If you mean to actually remove the element from the array, leaving your array with 4 elements, then you can use
numbers.splice(1);
This will remove the element in the index 1 from the array and return the section of the new array.

Array.fill a 2x2 array, then trying to set arr[0][0] = true fills the entire column? [duplicate]

This question already has answers here:
Why do changes made to a cell propagate to other cells in this 2 dimensional array created using fill?
(7 answers)
Closed 5 years ago.
I was doing some DFS stuff and wanted to use array that was the same size as the original matrix to toggle whether nodes were visited. I noticed when I tried to set the node as visited visited[r][c] = true, it ended up setting the entire column. I realized this only happens with Array(numberOfRows).fill(Array(numberOfCols).fill(false)).
Was wondering why it does that, and if there's a better way to initialize a 2D array with a set number of rows/cols?
var foo = [
[false,false],
[false,false],
];
foo[0][0] = true;
var bar = Array(2).fill(Array(2).fill(false));
bar[0][0] = true;
console.log(foo); // [[ true,false],[false,false]] (what I expected)
console.log(bar); // [[ true,false],[true,false]] (wtf?)
In the first case you have created two separate arrays with [] syntax, which are separate references to the separate objects. But the case is another with Array#fill.
Array#fill works with a single value. When you pass an array into the fill function to fill the outer array, only single array is created and its going to fill all items in the outer array. This means that two references of the single array are inserted in the outer array.
We can see it comparing the references of the first and second array.
var bar = Array(2).fill(Array(2).fill(false));
console.log(bar[0] === bar[1]);

Swapping elements in an array of objects [duplicate]

This question already has answers here:
Javascript swap array elements
(33 answers)
Closed 9 years ago.
I have an array of objects and I want to swap the position of two elements in the array.
I tried this:
var tempObject = array.splice(index, 1, array[index + 1]);
array.splice(index+1, 1, tempObject);
But it doesn't seem to work properly as it results in some weird errors. For example, I am unable to use methods of the object. Calling array[x].getName results in an error.
Can any body lend a helping hand here?
Just in case it is important, I have used object.prototype to add the methods.
The bug in your code is that splice returns an array of items, not a single item. Since you are extracting a single item, you could do:
var tempObject = array.splice(index, 1, array[index + 1])[0]; // get the item from the array
array.splice(index+1, 1, tempObject);
This answer provides a shorter version, also using splice:
array[index] = array.splice(index+1, 1, array[index])[0];
Another very interesting answer is both short and fast:
function identity(x){return x};
array[index] = identity(array[index+1], array[index+1]=array[index]);
JSFIDDLE
var array_of_numbers = [5,4,3,2,1,0],
swap = function(array,a,b){var tmp=array[a];array[a]=array[b];array[b]=tmp;};
swap(array_of_numbers,0,4);
// array_of_numbers now is [1,4,3,2,5,0]
Or you can do add the function to the Array.prototype:
JSFIDDLE
Array.prototype.swap = function(a,b){ var tmp=this[a];this[a]=this[b];this[b]=tmp;};
var array_of_numbers = [5,4,3,2,1,0];
array_of_numbers.swap(0,4);
// array_of_numbers now is [1,4,3,2,5,0]

Categories

Resources