Skip to content

Commit baaee9d

Browse files
committedJan 9, 2025
Add solution #2722
1 parent 52c7bbd commit baaee9d

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,7 @@
408408
2695|[Array Wrapper](./2695-array-wrapper.js)|Easy|
409409
2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy|
410410
2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium|
411+
2722|[Join Two Arrays by ID](./2722-join-two-arrays-by-id.js)|Medium|
411412
2724|[Sort By](./2724-sort-by.js)|Easy|
412413
3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy|
413414
3110|[Score of a String](./3110-score-of-a-string.js)|Easy|
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 2722. Join Two Arrays by ID
3+
* https://leetcode.com/problems/join-two-arrays-by-id/
4+
* Difficulty: Medium
5+
*
6+
* Given two arrays arr1 and arr2, return a new array joinedArray. All the objects in each
7+
* of the two inputs arrays will contain an id field that has an integer value.
8+
*
9+
* joinedArray is an array formed by merging arr1 and arr2 based on their id key. The length
10+
* of joinedArray should be the length of unique values of id. The returned array should be
11+
* sorted in ascending order based on the id key.
12+
*
13+
* If a given id exists in one array but not the other, the single object with that id should
14+
* be included in the result array without modification.
15+
*
16+
* If two objects share an id, their properties should be merged into a single object:
17+
* - If a key only exists in one object, that single key-value pair should be included in
18+
* the object.
19+
* - If a key is included in both objects, the value in the object from arr2 should override
20+
* the value from arr1.
21+
*/
22+
23+
/**
24+
* @param {Array} arr1
25+
* @param {Array} arr2
26+
* @return {Array}
27+
*/
28+
var join = function(arr1, arr2) {
29+
const map = new Map();
30+
[...arr1, ...arr2].forEach(obj => map.set(obj.id, { ...map.get(obj.id), ...obj }));
31+
return Array.from(map.values()).sort((a, b) => a.id - b.id);
32+
};

0 commit comments

Comments
 (0)
Please sign in to comment.