Merge Array
JavaScript
medium
25 mins
You are given two arrays of objects. Each object contains an id field and other key-value data. The goal is to merge the data by id.
- If an
idexists in both arrays, merge the properties. - If it exists only in one, include it as is.
- In case of conflict (same key but different values), prefer values from the second array.
Input:
- Two arrays of objects (each object has at least an
idkey)
Output:
- A new array with merged objects based on
id
Example Inputs & Outputs
Input: arr1 = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }] arr2 = [{ id: 2, age: 30 }, { id: 3, name: "Charlie" }] Output: [ { id: 1, name: "Alice" }, { id: 2, name: "Bob", age: 30 }, { id: 3, name: "Charlie" } ]
Constraints & Edge Cases
- Arrays can be of different lengths
- Objects may have overlapping or unique fields
- Duplicate
ids within a single array should not occur - If the same field exists in both and differs, use the value from the second array
Companies:
reddit
slack
ola
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
