I add some strings in an array.
console.log(arr1); // ['product_1']
let arr2 = arr1.push(name);
console.log(arr2); // 2
Why I receive number 2 in the second log when name is a String too?
I tried also let arr2 = arr1.slice().push(name); without success.
arr.push() modifies the arr itself and returns the length of the resulting array, to do what you want to do, you can do one of the two following methods
const name = "test";
arr1 = ['product_1'];
// Method 1
let arr2 = [...arr1, name]
console.log(arr2);
// Method 2
arr1.push(name);
console.log(arr1);
The number 2 in this case is the length of your array.
Documentation on MDN
Related
How come console shows "potato" instead of "JAN" when you console out arr2?
arr1[0]='Potato' is done after the line 4, so why arr2 is not equal to initial arr1? (array at line 1)
Both variables have an instance of the same array.
If you want to avoid that, make something like this instead const arr2 = [...arr1]. That will create new array with same elements as the first one.
You have to make new array from variable 1
Just try:
let arr2 = Array.from(arr1)
You can use const arr2 = [...arr1]; to immutable array clone
var arr1 = ['JAN', 'FEB'];
const arr2 = [...arr1];
arr1[0] = 'Potato';
console.log(arr2)
`
How to remove an element of an array and have that removed element saved in a variable:
var item = arr.remove(index)
You can use Array.prototype.splice for this purpose:
const arr = ['a', 'b', 'c'];
const removed = arr.splice(1, 1).pop();
console.log(arr) // ['a', 'c'];
console.log(removed) // 'b'
Note that in the example above, splice is chained with Array.prototype.pop - that's because splice, as mentioned by #Andreas, always returns an Array, so pop is used to extract the single value from Array returned by splice.
What you're looking for is splice. This takes as parameters the index of the item to remove, and the count of items from that to take out. Because you only want to remove 1 item, the 2nd parameter will always be 1. Splice also returns as an array, so we're indexing that [0] to get just the contents.
var arr = ['a','b','c'];
var item = arr.splice(1,1)[0]; // 'b'
Maybe something like this?
Array.prototype.remove=function(i){
var item=this[i]
this.splice(i,1)
return item
}
arr=[1,2,3]
item=arr.remove(1)
console.log(item) //2
console.log(arr) //[1,3]
I hope that this will help you!
It's always tricky to think Array.concat thing. Often, I just want to use mutable Array.push because I simply add extra-data on the immutable data. So, I usually do:
array[array.length] = newData;
I've asked a question related got some answers here: How to store data of a functional chain
const L = (a) => {
const m = a => (m.list ? m.list : m.list = [])
.push(a) && m;
//use `concat` and refactor needed instead of `push`
//that is not immutable
return m(a); // Object construction!
};
console.log(L);
console.log(L(2));
console.log(L(1)(2)(3))
some outputs:
{ [Function: m] list: [ 2 ] }
{ [Function: m] list: [ 1, 2, 3 ] }
I feel that push should be replaced with using concat, but still, push makes the code elegant simply because we don't want to prepare another object here.
Basically, I want to do:
arr1 = arr1.concat(arr2);
but, is there any way to write
arr1[arr1.length] = arr2;
which ends up with a nested array, and does not work.
You could assign a new array with a default array for not given m.list.
const L = (a) => {
const m = a => (m.list = (m.list || []).concat(a), m);
return m(a);
};
console.log(L.list);
console.log(L(2).list);
console.log(L(1)(2)(3).list);
You can use multiple parameters in Array.push so:
var a = [];
a.push(3, 4) // a is now [3, 4]
Combined with the ES6 spread syntax:
var a = [1, 2];
var b = [3, 4]
a.push(...b); // a is now [1, 2, 3, 4]
arr1[arr1.length] represents a single value, the value at index arr1.length.
Imagine this array
[ 1 , 2 , 3 , 4 ] // arr of length 4
^0 ^1 ^2 ^3 // indexes
If we say arr1[arr1.length] = someThing
We ask javascript to put something right here, and only here, at index 4:
[ 1 , 2 , 3 , 4 , ] // arr of length 4
^0 ^1 ^2 ^3 ^4 // add someThing in index 4
So, if we want to add something strictly with arr1[arr1.length], then we need to keep doing that for each index. for each meaning any kind of loop. E.G:
// Not recommended to use
var arr1 = [1,2,3];
var arr2 = [3,4,5];
while (arr2.length){
arr1[arr1.length] = arr2.shift();
}
console.log(arr1); // [1,2,3,3,4,5]
console.log(arr2); // []
But, as you can see, this method, or any similar one, even if optimized, is not the right approach. You need a concatenation.
Since you mention a functional one, which returns the resulting array, you can simply replace the initial array and make use of spread operator:
var arr1 = [1,2,3];
var arr2 = [3,4,5];
console.log(arr1 = [...arr1,...arr2]); // [1,2,3,3,4,5]
function myFunction()
{
var Arr2
if(Arr1!=null)
{
Arr2=Arr1
console.log("Arr2 before for: "+Arr2)
console.log("Arr1 before for: "+Arr1)
}
for(var index=-1+Arr2.length;index>=0;index--)
{
if(Arr2[index]=="to_delete")
{
Arr2.splice(index,1)
}
}
console.log("Arr1 after for: "+Arr1)
console.log("Arr2 after for: "+Arr2)
}
I create Arr2 in a function, Arr2=Arr1, the problem is that Arr1 is also being spliced during for, and from these last two console.logs i am informed that these 2 arrays are the same. (I only want to change Arr2)
When you do Arr2 = Arr1, you're just copying the reference to that array, you're not making a copy of the array itself. So both Arr1 and Arr2 will now refer to the same array.
Try changing
Arr2=Arr1
to
Arr2 = Arr1.slice()
which should copy all of the elements in Arr1 to the new Arr2. Check out Array.prototype.slice for more info.
You could just use filter Array method like this :
var arr2 = arr1.filter(x => x!="to_delete");
You are creating a reference to Arr1, not a new object.
Think of it this way:
Think of it this way: when you initialise Arr1, you're allocating it to a piece of memory on the heap. This reference is then given an address.
The assignment var Arr2 = Arr1 equals the same as saying, Arr2 is the same as Arr1 by reference. Which means it points to the same memory address.
If you want to make a copy of an object, a.k.a. pass it by value, you should use one of the following methods.
var Arr2 = Arr1.slice(0);
Keep in mind however that if your array contains objects, these are cloned by reference with this method. Example:
var Arr1 = [{a: 1, b: 2, c:3}, {d: 4, e: 5, f: 6}]
var Arr2 = Arr1.slice(0)
Arr1[0].a = 2;
console.log(Arr2[0].a) // this will output 2
If you want to easily do a deep clone without having to write the code to pass the object references by value, you can use something like lodash or just:
var Arr2 = JSON.parse(JSON.stringify(Arr1));
Which also works.
I have an array and simply want to get the element at index 1.
var myValues = new Array();
var valueAtIndex1 = myValues.getValue(1); // (something like this)
How can I get the value at the 1st index of my array in JavaScript?
You can access an element at a specific index using the bracket notation accessor.
var valueAtIndex1 = myValues[1];
On newer browsers/JavaScript engines (see browser compatibility here), you can also use the .at() method on arrays.
var valueAtIndex1 = myValues.at(1);
On positive indexes, both methods work the same (the first one being more common). Array.prototype.at() however allows you to access elements starting from the end of the array by passing a negative number. Passing -1 will give the last element of the array, passing -2 the second last, etc.
See more details at the MDN documentation.
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1].
See Accessing array elements for more info.
You can just use []:
var valueAtIndex1 = myValues[1];
indexer (array[index]) is the most frequent use. An alternative is at array method:
const cart = ['apple', 'banana', 'pear'];
cart.at(0) // 'apple'
cart.at(2) // 'pear'
If you come from another programming language, maybe it looks more familiar.
shift can be used in places where you want to get the first element (index=0) of an array and chain with other array methods.
example:
const comps = [{}, {}, {}]
const specComp = comps
.map(fn1)
.filter(fn2)
.shift()
Remember shift mutates the array, which is very different from accessing via an indexer.
Update 2022
With ES2022 you can use Array.prototype.at():
const myValues = [1, 2, 3]
myValues.at(1) // 2
at() also supports negative index, which returns an element from the end of the array:
const myValues = [1, 2, 3]
myValues.at(-1) // 3
myValues.at(-2) // 2
Read more:
MDN, JavascriptTutorial, Specifications
You can use [];
var indexValue = Index[1];
As you specifically want to get the element at index 1. You can also achieve this by using Array destructuring from ES6.
const arr = [1, 2, 3, 4];
const [zeroIndex, firstIndex, ...remaining] = arr;
console.log(firstIndex); // 2
Or, As per ES2022. You can also use Array.at()
const arr = [1, 2, 3, 4];
console.log(arr.at(1)); // 2