Update only the latest array in JavaScript - javascript

I am trying to update the array2 only and same values for array1. I wrote the following code,
array1 = [4232,3423,325,23421];
array2 = array1;
array2[0] = array2[0]/10;
array2[1] = array2[1]/100;
array2[2] = array2[2]/10;
console.log(array1, array2);
But the console shows both array1 and array2 are updated. How can I update the values of the array2 only?

In the case of a complex array, I think you can try deep copy method as following,
array1 = [4232,[24234,2324,[43,234]],3423,325,23421];
array2 = JSON.parse(JSON.stringify(array1));
array2[0] = array2[0]/10;
array2[1][2][1] = array2[1][2][1]/100;
array2[2] = array2[2]/10;
console.log(array1, array2);

You should shallow copy the array:
array1 = [4232,3423,325,23421];
array2 = [...array1];
array2[0] = array2[0]/10;
array2[1] = array2[1]/100;
array2[2] = array2[2]/10;
console.log(array1, array2);

You need to clone the array, or else both use the same reference.
array2 = [...array1];
If you have a nested array, you can do it this way [source]:
clone = (items) => items.map(item => Array.isArray(item) ? clone(item) : item);
array2 = clone(array1);

Related

How to replace array element with respect to Index on another array

I have one array which contains values array1 = [a,b,c,d,e,f,g] and another array contains index of array1 and the value to be replaced array2 = [[2,u],[3,x],[6,z]].
Now I want to replace value of array1 with respect to array2 please not array2 consist of [array1_position, value_to_be_replaced]
Now my new arra1 should look like this array1 = [a,b,u,x,e,f,z].
I can do this with for loop but its again time consuming. what trick can i use to replace the value quickly. I am just learning about arrays and have a little knowledge on it.
I don't think there is any shorthand for such a verbose question.
Something on top of my mind is
array2.forEach((el) => {
array1[el[0]] = el[1];
})
you could do this
array2.forEach(arr => {
const [index, replaced] = arr;
array1[index] = replaced;
});
You can take fromEntries of the other array then just map it:
var array1 = ['a','b','c','d','e','f','g'];
var array2 = [[2,'u'],[3,'x'],[6,'z']];
var d=Object.fromEntries(array2);
var result = array1.map((val, i)=> d[i] || val);
console.log(result);
With an ordered array2 by indices, you could take a closure over an index of this array and map the values from eithe the first array or the replacements array.
var array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
array2 = [[2, 'u'], [3, 'x'], [6, 'z']],
result = array1.map(
(j => (v, i) => i === array2[j][0] ? array2[j++][1] : v)
(0)
);
console.log(result);

filter array by integers by property of another array of objects

I have two arrays
var array1 = [1,2,3,4,5,6,2,1]
var array2 = [{id:1,name:"test"},{id:2,name:"test2"},{id:3,name:"test2"}]
I want to filter array1 by the id property of array2 , so that , the result of array1 should be :
array1 = [4,5,6]
Suggestion: Please try before ask
const array1 = [1,2,3,4,5,6,2,1]
const array2 = [{id:1,name:"test"},{id:2,name:"test2"},{id:3,name:"test2"}]
const result = array1.filter(i => !array2.find(x => x.id === i))
console.log(result)

Find elements in an array not contained in another array of objects

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));

Merging Two Array of Objects in angular 6

I have two arrays something like this.
array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}]
The result Should be Something like this.
array3 = [{name: 'arjun', place:'mysore', degree:'BE'}, {name:'kanka',place:'bangalore',degree:'MCA'}];
The above result Array doesn't have duplicate values now. Can anyone help please?
Assuming that you need to merge arrays by index and are of same length.
let array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
let array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}]
let array3 = array1.map((o,i) => ({...o, ...array2[i]}));
console.log(array3);
You can simply use a Array.map() and Object.assign()
array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}];
let result = array1.map((a)=>{
let obj2 = array2.find((b)=> a.name === b.name);
if(obj2)
Object.assign(a,obj2);
return a;
});
console.log(result);
I think you can use array#reduce to do something like this perhaps:
array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}]
var resultArray = array1.reduce((arr, e) => {
arr.push(Object.assign({}, e, array2.find(a => a.name == e.name)))
return arr;
}, [])
console.log(resultArray);
NOTE: It will also work if those arrays are of different length.
use the foreach like this
let array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
let array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}]
let array3 = [];
array1.forEach((item, index) => {
array3.push(item)
let degree = array2.find(e => e.name === item.name)
if(degree){
array3[index].degree = degree.degree
}
})
console.log(array3)
If both arrays are of the same length then this solution will work.
array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}]
const array3 = [];
for(let i=0; i < array1.length; i++){
array3.push(Object.assign(array1[i], array2[i]));
}
console.log(array3);
Working JSBin here.
Look here also: How can I merge properties of two JavaScript objects dynamically?
You can make an aggregation of properties by the name with reduce and map out the aggregated data to an array:
const array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
const array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}];
const objData = [...array1, ...array2].reduce((all, { name, place, degree }) => {
if (!all.hasOwnProperty(name)) all[name] = { name };
if (place) all[name].place = place;
if (degree) all[name].degree = degree;
return all;
}, {});
const result = Object.keys(objData).map(k => objData[k]);
console.log(result);

How do you merge the item values from 2 separate arrays in javascript?

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);

Categories

Resources