This question already has answers here:
Javascript Array Concat not working. Why?
(7 answers)
Closed 2 years ago.
I need to merge multiple array values using JavaScript but as per my code its not working. I am explaining my code below.
let result = [];
let arr1 = [1,2];
let arr2 = [3,4];
let arr3 = [5,6];
result.concat(arr1);
result.concat(arr2);
result.concat(arr3);
console.log(result);
Here I am expecting output as [1,2,3,4,5,6] but as per my code its coming [].
Concat is a pure operator. It means it produces a new array instead of changing the one that is calling it.
let result = [];
let arr1 = [1,2];
let arr2 = [3,4];
let arr3 = [5,6];
result.concat(arr1); // returns an array
result.concat(arr2); // returns an array
result.concat(arr3); // returns an array
if you want to change a result array you can do it like this:
let result = [];
let arr1 = [1,2];
let arr2 = [3,4];
let arr3 = [5,6];
result = result.concat(arr1);
result = result.concat(arr2);
result = result.concat(arr3);
or
let result = [];
let arr1 = [1,2];
let arr2 = [3,4];
let arr3 = [5,6];
result.push(...arr1);
result.push(...arr2);
result.push(...arr3);
push is an impure operator so it is changing 'result' array. I am using a destructuring here to pass all of arr elements to push as separate arguments.
As #VLAZ suggested, you should store the returned array:
var a = [1, 2, 3];
var b = [4, 5, 6];
var c = a.concat(b);
console.log(c); // c is [1, 2, 3, 4, 5, 6]
Related
I am having a little difficuly coming up with a solution to my problem.
I am trying to get the item at an index of a collection of arrays. I cannot actually concatenate the arrays, they need to stay seperate.
Normally, to get the 3rd item from an array, you would do:
function getItemFromJustOneArray(index){
var my_array = [1,2,3,4,5,6];
return my_array[index];
}
getItemFromJustOneArray(2); // returns 3
However, I have a bunch of arrays (could be any amount of arrays) and these arrays cannot be merged into one.
function getItemFromMultipleArrays(index){
var array1 = [1,2];
var array2 = [3,4,5];
var array3 = [6];
// I cannot use concat (or similar) to merge the arrays,
// they need to stay seperate
// also, could be 3 arrays, but could also be 1, or 5...
// return 3;
}
getItemFromMultipleArrays(2); // SHOULD RETURN 3
I have tried a bunch of lines that loops over the array, but I cannot really get a working solution.
Does someone know an elegant solution to this problem?
Nest all the arrays in another array. Then loop over that array, decrementing index by each array's length until it's within the length of the current element. Then you can return the appropriate element of that nested array.
function getItemFromMultipleArrays(index) {
var array1 = [1, 2];
var array2 = [3, 4, 5];
var array3 = [6];
var all_arrays = [array1, array2, array3];
var i;
for (i = 0; i < all_arrays.length && index >= all_arrays[i].length; i++) {
index -= all_arrays[i].length;
}
if (i < all_arrays.length) {
return all_arrays[i][index];
}
}
console.log(getItemFromMultipleArrays(2)); // SHOULD RETURN 3
Why not spread the arrays to a new one and use the index for the value?
function getItemFromMultipleArrays(index) {
const
array1 = [1, 2],
array2 = [3, 4, 5],
array3 = [6];
return [...array1, ...array2, ...array3][index];
}
console.log(getItemFromMultipleArrays(2)); // 3
Another approach by using an offset for iterating arrays.
function getItemFromMultipleArrays(index) {
const
array1 = [1, 2],
array2 = [3, 4, 5],
array3 = [6],
temp = [array1, array2, array3];
let j = 0;
while (index >= temp[j].length) index -= temp[j++].length;
return temp[j][index];
}
console.log(getItemFromMultipleArrays(2)); // 3
console.log(getItemFromMultipleArrays(5)); // 6
this should do it, just copying all the arrays into a "big" one and accessing it (added a helping function)
// this function takes any amount of arrays and returns a new
// "concatted" array without affecting the original ones.
function connectArrays(...arrays) {
return [...arrays.flat()];
}
function getItemFromMultipleArrays(index) {
var array1 = [1,2];
var array2 = [3,4,5];
var array3 = [6];
var allArrays = connectArrays(array1, array2, array3);
return allArrays[index];
}
getItemFromMultipleArrays(2); // SHOULD RETURN 3
This question already has answers here:
Why does changing an Array in JavaScript affect copies of the array?
(12 answers)
Closed 2 years ago.
Let's say I have this code:
var arr = [1, 2, 3, 4, 5];
var arr1 = arr;
arr.splice(Math.min(...arr), 1);
But for some reason, the value of arr is the same as arr1. What if I want arr to be different than arr1 and be independent of its updating?
Your issue is this line:
var arr1 = arr;
According to the situation you describe you want to copy the array.
But with this line you're just assigning it to another variable instead of copying.
So in fact, without copying, the arrays are the same.
In order to copy just do something like this:
let copy = array.slice(0);
/* or (will not work for large arrays) */
let copy = [...array];
This should do the trick for you
var arr = [1, 2, 3, 4, 5];
var arr1 = arr.slice();
arr.splice(Math.min(...arr), 1);
console.log(arr);
console.log(arr1);
Arrays are objects, so you can copy them the same way
var x = [1, 2, 3],
y = Object.assign([], x);
x[0] = 16;
console.log(x);
console.log(y);
I have an array arr1 = [1,2,3,4,5]
There is another array of objects arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]
I am looking for find elements in arr1 which are not in arr2. The expected output is [1,3,5]
I tried the following but it doesn't work.
const arr = arr1.filter(i => arr2.includes(i.id));
Can you please help?
A solution with O(arr2.length) + O(arr1.length) complexity in Vanilla JS
var arr1= [1,2,3,4,5];
var arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}];
var tmp = arr2.reduce(function (acc, obj) {
acc[obj['id']] = true;
return acc;
}, {});
var result = arr1.filter(function(nr) {
return !tmp.hasOwnProperty(nr);
})
arr2 is an array of objects, so arr2.includes(i.id) doesn't work because i (an item from arr1) is a number, which doesn't have an id property, and because arr2 is an array of objects.
Turn arr2's ids into a Set first, then check whether the set contains the item being iterated over:
const arr1 = [1,2,3,4,5];
const arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}];
const ids = new Set(arr2.map(({ id }) => id));
const filtered = arr1.filter(num => !ids.has(num));
console.log(filtered);
You can try with Array.prototype.some():
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
const arr1 = [1,2,3,4,5]
const arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]
const arr = arr1.filter(i => !arr2.some(j => j.id == i));
console.log(arr);
We can use the filter method like below to check the condition required
var arr1 = [1, 2, 3, 4, 5]
var arr2 = [{ 'id': 2, 'name': 'A' }, { 'id': 4, 'name': 'B' }]
var ids = [];
arr2.forEach(element => {
ids.push(element['id'])
});
var result = arr1.filter(s => ids.indexOf(s) < 0)
console.log(result)
let arr1= [1,2,3,4,5];
let arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]
let arr2Ids=arr2.map(item=>item.id);
let result=arr1.filter(n => !arr2Ids.includes(n));
You can use find on arr2 instead of includes since arr2 is composed of object
const arr = arr1.filter(i => !arr2.find(e => e.id===i));
I'm not looking to push the values from one array into another, or concatenate them but simply sum the item values from each - either into a new array, or alternatively amending either arrayOne or arrayTwo with the values from the other e.g.
var arrayOne = [1,2,3,4,5]
var arrayTwo = [2,4,6,8,10]
// loop / function..
var newArray = [3,6,9,12,15]
OR arrayOne = [3,6,9,12,15]
I thought this would be straightforward but this requires 2 loops running at the same time?
Thanks for your help!
var arrayOne = [1,2,3,4,5];
var arrayTwo = [2,4,6,8,10];
var newArray = [];
newArray = arr1.map((item,index)=>{
return item + arr2[index]
});
You could collect all wanted array for adding values at the same index in an array and reduce the arrays.
This works with an arbitrary count of arrays.
var array1 = [1, 2, 3, 4, 5],
array2 = [2, 4, 6, 8, 10],
result = [array1, array2].reduce(
(a, b) => (b.forEach((v, i) => a[i] = (a[i] || 0) + v), a)
);
console.log(result);
You can use Array's map():
var arrayOne = [1,2,3,4,5];
var arrayTwo = [2,4,6,8,10];
var newArray = arrayOne.map( (item, i) => item += arrayTwo[i] );
console.log(newArray);
var arr = [1,2,3,4];
I need to get the last one and then delete it from an array called arr:
var arr = [1,2,3]
You want to do exactly what the pop method does:
var arr = [1,2,3,4];
//...
var last = arr.pop(); // returns 4, and arr will contain now [1, 2, 3]