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);
Related
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)
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);
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 want to sort array1 using array2.
var array1 = ["cat","dog","mouse","elephant","ant","cow","goat","hen"];
var array2 = ["mouse","cow","goat"];
The result should look like
var another_array = ["mouse","cow","goat", "bird"--- then rest of the values in array1]
Just taken from object with the order the value or Infinity for the delta.
var array1 = ["cat", "dog", "mouse", "elephant", "ant", "cow", "goat", "hen"],
array2 = ["mouse", "cow", "goat"],
order = array2.reduce((r, k, i) => (r[k] = i + 1, r), {});
array1.sort((a, b) => (order[a] || Infinity) - (order[b] || Infinity));
console.log(array1);
Sounds like you're looking for concatenation and filtering:
>>> array2.concat(array1.filter(i => !array2.includes(i)))
["mouse", "cow", "goat", "cat", "dog", "elephant", "ant", "hen"]
Something like this - concatenation and a filter
const array1 = ["cat","dog","mouse","elephant","ant","cow","goat","hen"];
const array2 = ["mouse","cow","goat"];
const anotherArray = [...array2,
"bird",
...array1.filter(item => !array2.includes(item))]
console.log(anotherArray)
Use concat function
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
console.log(children)
We have same two arrays to groupby theme by index.
Two arrays with same length and different value like blow.
How to groupby two array with their index by ES6 reduce or lodash?
array1 = [1,2,3,4] OR [{a:1},{b:2},{c:3},{d:4}]
array2 = [5,6,7,8] OR [{e:5},{f:6},{g:7},{h:8}]
finalArray = [[1,5],[2,6],[3,7],[4,8]]
I'm trying with different ways like group by with reduce in es6 or lodash concat but i can't find best solution for my problems.
Try this:
let array1 = [1, 2, 3, 4];
let array2 = [5, 6, 7, 8];
let res = array1.map((value, index) => {
return [value, array2[index]]
})
console.log(res);
If it is array of objects
let array1 = [{a:1},{b:2},{c:3},{d:4}];
let array2 = [{e:5},{f:6},{g:7},{h:8}];
let res = array1.map((value, index) => {
return [Object.values(value)[0],Object.values(array2[index])[0]]
})
console.log(res)
Use lodashes zip function
// _ is lodash
const array1 = [1,2,3,4]
const array2 = [5,6,7,8]
console.log(_.zip(array1, array2))
result
[ [ 1, 5 ], [ 2, 6 ], [ 3, 7 ], [ 4, 8 ] ]
If you are working with the array of objects. Get just the values using Object.values and grab the 0th element.
const array3 = [{a:1},{b:2},{c:3},{d:4}];
const array4 = [{e:5},{f:6},{g:7},{h:8}];
function firstval(ob){
return Object.values(ob)[0]
}
console.log(_.zip(array3.map(firstval), array4.map(firstval)))
You can also write your own zip. This is a limited version. That handles only 2 elements, doesn't accept or return generators etc.
It could easily be extended to take a spread operator and therefore any number of arguments. You don't seem to need that level of flexibility though.
function zip(a, b) {
const num = Math.min(a.length, b.length);
const result = [];
for(i = 0; i < num; i++) result.push([a[i], b[i]]);
return result;
}
Following code works under these assumptions:
all input arrays have same length
if array element is object, it has only one property
function getValue(element) {
if (typeof element === 'object') {
return Object.values(element).pop()
} else {
return element
}
}
function zipArrays(arr1, arr2) {
return arr1.reduce((acc, elm1, index) => {
const elm2 = arr2[index]
const elm = [getValue(elm1), getValue(elm2)]
acc.push(elm)
return acc
}, [])
}
// usage:
const array1 = [1,2,3,4] // OR [{a:1},{b:2},{c:3},{d:4}]
const array2 = [5,6,7,8] // OR [{e:5},{f:6},{g:7},{h:8}]
const finalArray = zipArrays(array1, array2)