Skip to content

Commit 71ae9ca

Browse files
authored
Create 1122-relative-sort-array.js
1 parent 9fcc03e commit 71ae9ca

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

1122-relative-sort-array.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[]} arr1
3+
* @param {number[]} arr2
4+
* @return {number[]}
5+
*/
6+
const relativeSortArray = function(arr1, arr2) {
7+
const hash = {}
8+
const res = []
9+
arr1.forEach(el => {
10+
if(hash.hasOwnProperty(el)) hash[el] += 1
11+
else hash[el] = 1
12+
})
13+
for(let i = 0, len = arr2.length; i < len; i++) {
14+
res.push(...makeArr(arr2[i], hash[arr2[i]]))
15+
delete hash[arr2[i]]
16+
}
17+
const keys = Object.keys(hash).sort((a, b) => a - b)
18+
for(let i = 0, len = keys.length; i < len; i++) {
19+
res.push(...makeArr(keys[i], hash[keys[i]]))
20+
}
21+
return res
22+
};
23+
24+
function makeArr(el, num) {
25+
return new Array(num).fill(el)
26+
}

0 commit comments

Comments
 (0)