Skip to content

Commit a77f298

Browse files
committed
added function
1 parent 0a5ad98 commit a77f298

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Relative Sort Array/code.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* @param {number[]} arr1
3+
* @param {number[]} arr2
4+
* @return {number[]}
5+
*/
6+
var relativeSortArray = function(arr1, arr2) {
7+
const hash = {};
8+
const remaining = []
9+
for(let n of arr2){
10+
hash[n] = hash[n] >= 0 ? hash[n] + 1 : 0
11+
}
12+
13+
for(let n of arr1){
14+
hash[n] = hash[n] >= 0 ? hash[n] + 1 : undefined
15+
if(hash[n] === undefined) remaining.push(n)
16+
}
17+
18+
remaining.sort((a,b)=>a-b)
19+
20+
for(let i = 0; i < arr2.length; i++){
21+
const curr = arr2[i]
22+
if(hash[curr]-- > 1){
23+
arr2.splice(i,0,curr)
24+
i--
25+
}
26+
}
27+
return arr2.concat(remaining)
28+
};
29+

0 commit comments

Comments
 (0)