Reputation: 35
I have two arrays:
var scores = [{ name: "Bob", score: 19 }, { name: "Harry", score: 27 }, { name: "Janelle", score: 35 }];
var ranks = [{ name: "Bob", rank: 3 }, { name: "Harry", rank: 2 }, { name: "Janelle", rank: 1 }];
I want to merge the two arrays and add "rank" to all the corresponding arrays without repeating "name". Just like INDEX MATCH in Excel.
Upvotes: 0
Views: 30
Reputation: 11001
Go thru both arrays and build one object with keys as unique name
and accumulate values. Use Object.values
to values as an array.
var scores = [
{ name: "Bob", score: 19 },
{ name: "Harry", score: 27 },
{ name: "Janelle", score: 35 }
];
var ranks = [
{ name: "Bob", rank: 3 },
{ name: "Harry", rank: 2 },
{ name: "Janelle", rank: 1 }
];
const merge = (arr1, arr2) => {
const res = {};
[...arr1, ...arr2].forEach(item =>
Object.assign(res, { [item.name]: { ...res[item.name], ...item } })
);
return Object.values(res);
};
console.log(merge(scores, ranks));
Upvotes: 0
Reputation: 545
You can create a function named mergeArrays
that accepts the source array, the destination array, and a key to match array items with. Using Array.map
iterate through the source
array, then when a destination
array item with the same key
value is found, assign the object's values and return the map. Note that this will not only assign rank
to the source
array, but all the values in the destination
array. Seeming as how in the example rank
is the only differing property it should not be a problem.
var scores = [
{ name: "Bob", score: 19 },
{ name: "Harry", score: 27 },
{ name: "Janelle", score: 35 }
]
var ranks = [
{ name: "Bob", rank: 3 },
{ name: "Harry", rank: 2 },
{ name: "Janelle", rank: 1 }
]
const mergeArrays = (source, destination, key) => {
return scores.map((score) => {
let rank = ranks.find((rank) => rank[key] === score[key])
return Object.assign(score, rank)
})
}
console.log(mergeArrays(scores, ranks, 'name'))
Upvotes: 1