This question already has answers here:
Merge two array of objects based on a key
(23 answers)
Closed 1 year ago.
I have two arrays:
Array 1:
[
{
name: 'Bob',
traits: {
id: 1
}
}, {
name: 'Karl',
traits: {
id: 2
}
}, {
name: 'Joseph',
traits: {
id: 3
}
}
]
Array 2:
[
{
name: 'Karl',
user_id: 2,
dog: 'Rottweiler'
}, {
name: 'Joseph',
user_id: 3,
dog: 'Poodle'
}, {
name: 'Bob',
user_id: 1,
dog: 'Puppy'
}
]
Desired outcome:
I want to be able to merge the second array into the first array by finding what element user_id matches with id and then adding the object to array.
For example:
array 1 obj
{
name: 'Bob',
traits: {
id: 1
}
}
Since the id matches with array 2 obj user_id:
{
name: 'Bob',
user_id: 1,
dog: 'Puppy'
}
Final outcome will be:
{
name: 'Bob',
traits: {
name: 'Bob',
user_id: 1,
dog: 'Puppy'
}
}
arr2.forEach((obj) => {
const idx = arr1.findIndex((o) => o.traits.id === obj.user_id);
if (idx !== -1) {
arr1[idx] = { ...arr1[idx], traits: { ...obj } }
}
})
console.log(arr1[0]) // { name: 'Bob', traits: { name: 'Bob', user_id: 1, dog: 'Puppy' } }
Turn the second array into a map keyed by user_id, and then iterate the first array. Find the corresponding object in the map, and spread the matching object value into the traits property:
let arr1 = [{name: 'Bob',traits: {id: 1}},{name: 'Karl',traits: {id: 2}},{name: 'Joseph',traits: {id: 3}}];
let arr2 = [{name: 'Karl', user_id: 2,dog: 'Rottweiler'},{name: 'Joseph', user_id: 3,dog: 'Poodle'},{name: 'Bob',user_id: 1,dog: 'Puppy'}];
let map = new Map(arr2.map(item => [item.user_id, item]));
let result = arr1.map(item => {
let traits = map.get(item.traits.id);
return traits ? { ...item, traits} : item;
});
console.log(result);
As lookup in a map has an amortised time complexity of O(1), this is more efficient than finding the key in the array on every iteration (like with calling find).
You can easily achieve this result using map and find. Just map over the first array and find the element with obj.traits.id in the arr2. then return the desired result.
const arr1 = [
{
name: "Bob",
traits: {
id: 1,
},
},
{
name: "Karl",
traits: {
id: 2,
},
},
{
name: "Joseph",
traits: {
id: 3,
},
},
];
const arr2 = [
{
name: "Karl",
user_id: 2,
dog: "Rottweiler",
},
{
name: "Joseph",
user_id: 3,
dog: "Poodle",
},
{
name: "Bob",
user_id: 1,
dog: "Puppy",
},
];
const result = arr1.map((obj) => {
const { name, traits } = obj;
const isExist = arr2.find((o) => o.user_id === traits.id);
if (isExist) {
return { name, traits: { ...isExist } };
}
return obj;
});
console.log(result);
let a = [
{
name: 'Bob',
traits: {
id: 1
}
}, {
name: 'Karl',
traits: {
id: 2
}
}, {
name: 'Joseph',
traits: {
id: 3
}
}
];
let b = [
{
name: 'Karl',
user_id: 2,
dog: 'Rottweiler'
}, {
name: 'Joseph',
user_id: 3,
dog: 'Poodle'
}, {
name: 'Bob',
user_id: 1,
dog: 'Puppy'
}
];
a.map(aobj =>{
let sameIdObj = b.find( bobj => bobj.user_id === aobj.traits.id )
sameIdObj && (aobj.traits = sameIdObj)
})
console.log(a);
Related
I have two arrays. look by id, find FIRST occurrence of element from Array1 IN Array2, Take the Index that element is found at in Array2, and make a new Array where element in Array1 is moved to the new index found in Array2. in Array1 {id: 001} is at index 0, I would like it to be in a new Array at index 1 (index it is FIRST found in Array2). {id: 002} is at index 1 in Array1, I would like this to be in the new Array at index 3( index it is FIRST found in Array2) so on....
const Array1 = [
{
id: '001',
school: "blue springs"
},
{
id: '002',
school: "sycamore hills"
},
{
id: '003',
school: "moreland ridge"
},
{
id: '004',
school: "grain valley"
}
]
const Array2 = [
{
id: '003',
participant: "Susan"
},
{
id: '001',
participant: "Henry"
},
{
id: '003',
participant: "Justin" <---- if 003 exists do not duplicate the return array, this is my issue....
},
{
id: '004',
participant: "Jessica"
},
{
id: '002',
participant: "Carly"
},
{
id: '001',
participant: "Chloe" <---- if 001 exists do not duplicate the return array, this is my issue....
}
// got this far,
const finder = Array1.map((el) => { return Array2.findIndex((el2) => { return el2.id === el.id}) })
console.log(finder)
// [ 1, 4, 0, 3 ] <--- need to move Array1 objects to these new indexes
expected output
const Result = [
{
id: '003',
school: "moreland ridge"
},
{
id: '001',
school: "blue springs"
},
{
id: '004',
school: "grain valley"
},
{
id: '002',
school: "sycamore hills"
}
]
You first filter to remove duplicates on Array2, and then look for a match in Array1 regarding id's
const Array1 = [
{
id: '001',
school: "blue springs"
},
{
id: '002',
school: "sycamore hills"
},
{
id: '003',
school: "moreland ridge"
},
{
id: '004',
school: "grain valley"
}
]
const Array2 = [
{
id: '003',
participant: "Susan"
},
{
id: '001',
participant: "Henry"
},
{
id: '003',
participant: "Justin" // <---- if 003 exists do not duplicate the return array, this is my issue....
},
{
id: '004',
participant: "Jessica"
},
{
id: '002',
participant: "Carly"
},
{
id: '001',
participant: "Chloe" // <---- if 001 exists do not duplicate the return array, this is my issue....
}
]
const alreadyShown = {};
const res = Array2.filter( el => {
if (!alreadyShown[el.id]){
alreadyShown[el.id] = true;
return true;
}
return false;
}).map( x => Array1.find( y => x.id === y.id ) || x);
console.log(res)
NOTE: I included a logical OR to provide a fallback case, but this is not defined in OP request
I think you just need to sort the first array by the uniqueness of the identifier in the second array
const Array1 = [{id: '001',school: "blue springs"},{id: '002',school: "sycamore hills"},{id: '003',school: "moreland ridge"},{id: '004',school: "grain valley"}];
const Array2 = [{id: '003',participant: "Susan"},{id: '001',participant: "Henry"},{id: '003',participant: "Justin"},{id: '004',participant: "Jessica"},{id: '002',participant: "Carly"},{id: '001',participant: "Chloe" }];
const idOrder = Array2.map(({ id }) => id).filter((v, i, a) => a.indexOf(v)===i);
console.log('Order:', idOrder );
const sortedByOrder = Array1.sort(({ id: id1 }, { id: id2 }) =>
idOrder.indexOf(id1) - idOrder.indexOf(id2));
console.log('Result:', sortedByOrder);
.as-console-wrapper{min-height: 100%!important; top: 0}
I see that all the loops for objects returns the key as string and the value, but I want to operate on the keys of the object itself. If I have this object:
const data = {
person1: [
{ id: 1, name: Mike, age: 24 },
{ id: 2, name: Bob, age: 31 }
],
person2: [
{ id: 3, name: Christin, age: 21 },
{ id: 4, name: Michelle, age: 33 }
],
}
const removePersonById = (id) => {
// Check which person the id belongs to and remove that person
const persons = Object.keys(data).map(person => ...)
}
I wanted to loop through data and run .includes on each person in order to remove them by the id, but I am at a loss on how to do that.
You can loop through all keys and delete that the person you want by id using the filter() method
const removePersonById = (id) => {
var all = Object.keys(data);
for(let person of all){
data[person] = data[person].filter(a => a.id!=id);
}
}
You could get the values and find the index. Then splice.
const
removePersonById = id => {
Object.values(data).forEach(a => {
const index = a.findIndex(o => o.id === id);
if (index !== 0) a.splice(index, 1);
});
};
You could use .some()
const data = {
person1: [
{ id: 1, name: "Mike", age: 24 },
{ id: 2, name: "Bob", age: 31 }
],
person2: [
{ id: 3, name: "Christin", age: 21 },
{ id: 4, name: "Michelle", age: 33 }
],
}
const removePersonById = (id) => {
// Check which person the id belongs to and remove that person
Object.keys(data).map(person => {
if (data[person].some(p => p.id === id)) delete data[person];
})
}
removePersonById(3)
console.log(data)
Use Object.entries() so you can iterate over the keys and values together. Then you can test the value to see if the id is found.
Then use the delete operator to remove that key from the object.
const removePersonById = id => {
delete data[id];
};
const data = {
person1: [
{ id: 1, name: "Mike", age: 24 },
{ id: 2, name: "Bob", age: 31 }
],
person2: [
{ id: 3, name: "Christin", age: 21 },
{ id: 4, name: "Michelle", age: 33 }
],
};
const removePersonById = (id) =>
Object.entries(data).forEach(([key, value]) => {
if (value.some(({id: personid}) => personid == id)) {
delete data[key];
}
});
removePersonById(3);
console.log(data);
let data = {
person1: [
{ id: 1, name: "Mike", age: 24 },
{ id: 2, name: "Bob", age: 31 }
],
person2: [
{ id: 3, name: "Christin", age: 21 },
{ id: 4, name: "Michelle", age: 33 }
],
}
const removePersonById = (id) => {
// Check which person the id belongs to and remove that person
data = Object.keys(data).reduce((acc,key) => {
if(data[key].some(person=>person.id===id)) return acc
acc[key]= data[key]
return acc
}, {})
console.log(`Remove person with ID ${id}: `,data)
}
removePersonById(1)
I want to join a with b using lodash here is my data
const a =
[ { id: 1, job: 'engineer' }
, { id: 2, job: 'police' }
, { id: 3, job: 'thief' }
]
const b =
[ { name: 'test1', score: 1, aId: [ 1, 2 ] }
, { name: 'test2', score: 3, aId: [ 1, 3 ] }
]
Here is my output that I want
const result =
[ { id: 1, job: 'engineer', score: [ {name: 'test1'}, {name: 'test2'} ] }
, { id: 2, job: 'police', score: [] }
, { id: 3, job: 'thief', score: [ {name: 'test 3'} ] }
]
this is what I try I'm using 2 map data and inside the second map I use include check between 2 arrays..
_.map(a, function(data:any) {
const name = _.map(b, function(dataB:any) {
// in here I check
const isValid = dataB.aId.includes(a.id)
if(isValid){
return {
name = dataB.name
}
}
})
return {
id: data.id
job: data.job
score: name
}
});
this method also work but is their any better method than using 2 map ?
Reduce b to a map of id to array of tests, and then map a, and take the relevant array from the map to create each object:
const a =
[ { id: 1, job: 'engineer' }
, { id: 2, job: 'police' }
, { id: 3, job: 'thief' }
]
const b =
[ { name: 'test1', score: 1, aId: [ 1, 2 ] }
, { name: 'test2', score: 3, aId: [ 1, 3 ] }
]
const bMap = b.reduce((acc, { name, aId }) => {
const nameObject = { name }
aId.forEach(id => {
if(!acc.has(id)) acc.set(id, [])
acc.get(id).push(nameObject)
})
return acc
}, new Map())
const result = a.map(o => ({ ...o, scores: bMap.get(o.id) }))
console.log(result)
This question already has answers here:
Create array of unique objects by property
(17 answers)
Closed 3 years ago.
I have an object that looks like this:
const posts = [
{ id: 0, user: { id: 5564, name: 'john'} },
{ id: 1, user: { id: 5564, name: 'john'} },
{ id: 2, user: { id: 5560, name: 'jane'} }
]
I need an array of the unique user hashes like this:
[
{ id: 5564, name: 'john'},
{ id: 5560, name: 'jane'}
]
I'm able to retrieve all the users attributes from the posts array by doing:
const postUsers = posts.map(post => post.user)
which returns:
[
{ id: 5564, name: 'john'},
{ id: 5564, name: 'john'},
{ id: 5560, name: 'jane'}
]
where user john is listed twice
I've been able to get my desired result by doing:
const unique = {};
const uniqueUsers = [];
for(var i in postUsers){
if(typeof(unique[postUsers[i].id]) == "undefined"){
uniqueUsers.push(postUsers[i]);
}
unique[postUsers[i].id] = 0;
};
uniqueUsers
but there must be a cleaner way.
I've also been able to return the unique ids of all users by doing:
var ids = posts.map(post => post.user.id)
var uniqueIds = Array.from(new Set(ids)).sort();
which returns
[5564, 5560]
not sure if that helps. this article helped me a little https://medium.com/tomincode/removing-array-duplicates-in-es6-551721c7e53f
You could take a Map and get only the unique users.
const
posts = [{ id: 0, user: { id: 5564, name: 'john'} }, { id: 1, user: { id: 5564, name: 'john'} }, { id: 2, user: { id: 5560, name: 'jane'} }],
unique = Array.from(posts.reduce((m, { user }) => m.set(user.id, user), new Map).values());
console.log(unique);
If you don't mind using lodash you can do something like
const users = _map.(posts, 'user') // To get the list of users
_.uniqBy(users, 'id') // to get the uniq ones
Put the objects directly in uniqueUsers, then use Object.values() at the end to convert the object to an array.
const posts = [
{ id: 0, user: { id: 5564, name: 'john'} },
{ id: 1, user: { id: 5564, name: 'john'} },
{ id: 2, user: { id: 5560, name: 'jane'} }
];
let uniqueUsers = {};
posts.forEach(({user}) => uniqueUsers[user.id] = user);
uniqueUsers = Object.values(uniqueUsers);
console.log(uniqueUsers);
Use reduce to reduce the array by checking if the value is already in the array. If it is already in the array, return the current state of the array, otherwise add the item to the array.
const posts = [
{ id: 0, user: { id: 5564, name: 'john'} },
{ id: 1, user: { id: 5564, name: 'john'} },
{ id: 2, user: { id: 5560, name: 'jane'} }
]
const r = posts.map(i => i.user).reduce((acc, itm) => {
return !acc.find(i => i.id == itm.id) && acc.concat(itm) || acc
}, [])
console.log(r)
This question already has answers here:
How to get the difference between two arrays of objects in JavaScript
(22 answers)
Closed 1 year ago.
I need some help. How can I get the array of the difference on this scenario:
var b1 = [
{ id: 0, name: 'john' },
{ id: 1, name: 'mary' },
{ id: 2, name: 'pablo' },
{ id: 3, name: 'escobar' }
];
var b2 = [
{ id: 0, name: 'john' },
{ id: 1, name: 'mary' }
];
I want the array of difference:
// [{ id: 2, name: 'pablo' }, { id: 3, name: 'escobar' }]
How is the most optimized approach?
I´m trying to filter a reduced array.. something on this line:
var Bfiltered = b1.filter(function (x) {
return x.name !== b2.reduce(function (acc, document, index) {
return (document.name === x.name) ? document.name : false
},0)
});
console.log("Bfiltered", Bfiltered);
// returns { id: 0, name: 'john' }, { id: 2, name: 'pablo' }, { id: 3, name: 'escobar' } ]
Thanks,
Robot
.Filter() and .some() functions will do the trick
var b1 = [
{ id: 0, name: 'john' },
{ id: 1, name: 'mary' },
{ id: 2, name: 'pablo' },
{ id: 3, name: 'escobar' }
];
var b2 = [
{ id: 0, name: 'john' },
{ id: 1, name: 'mary' }
];
var res = b1.filter(item1 =>
!b2.some(item2 => (item2.id === item1.id && item2.name === item1.name)))
console.log(res);
You can use filter to filter/loop thru the array and some to check if id exist on array 2
var b1 = [{ id: 0, name: 'john' }, { id: 1, name: 'mary' }, { id: 2, name: 'pablo' }, { id: 3, name: 'escobar' } ];
var b2 = [{ id: 0, name: 'john' }, { id: 1, name: 'mary' }];
var result = b1.filter(o => !b2.some(v => v.id === o.id));
console.log(result);
Above example will work if array 1 is longer. If you dont know which one is longer you can use sort to arrange the array and use reduce and filter.
var b1 = [{ id: 0, name: 'john' }, { id: 1, name: 'mary' }, { id: 2, name: 'pablo' }, { id: 3, name: 'escobar' } ];
var b2 = [{ id: 0, name: 'john' }, { id: 1, name: 'mary' }];
var result = [b1, b2].sort((a,b)=> b.length - a.length)
.reduce((a,b)=>a.filter(o => !b.some(v => v.id === o.id)));
console.log(result);
Another possibility is to use a Map, allowing you to bring down the time complexity to O(max(n,m)) if dealing with a Map-result is fine for you:
function findArrayDifferences(arr1, arr2) {
const map = new Map();
const maxLength = Math.max(arr1.length, arr2.length);
for (let i = 0; i < maxLength; i++) {
if (i < arr1.length) {
const entry = arr1[i];
if (map.has(entry.id)) {
map.delete(entry.id);
} else {
map.set(entry.id, entry);
}
}
if (i < arr2.length) {
const entry = arr2[i];
if (map.has(entry.id)) {
map.delete(entry.id);
} else {
map.set(entry.id, entry);
}
}
}
return map;
}
const arr1 = [{id:0,name:'john'},{id:1,name:'mary'},{id:2,name:'pablo'},{id:3,name:'escobar'}];
const arr2 = [{id:0,name:'john'},{id:1,name:'mary'},{id:99,name:'someone else'}];
const resultAsArray = [...findArrayDifferences(arr1,arr2).values()];
console.log(resultAsArray);