I want do sort a array according another array
For Example:
let arrayParent = [6, 5, 4, 3, 2, 1];
let arrayChild = [3, 1, 2];
let myAnswer = [3, 1, 2, 6, 5, 4];
In fact, I want the arrayChild at first and then etc.
I want do sort a array according another array
For Example:
let arrayParent = [6, 5, 4, 3, 2, 1];
let arrayChild = [3, 1, 2];
let myAnswer = [3, 1, 2, 6, 5, 4];
In fact, I want the arrayChild at first and then etc.
You could use sorting with map and take the index of the wanted top values or move the other values to the bottom by using Infinity
and their original index.
This works for more than one same value.
var array = [6, 5, 4, 3, 2, 1],
children = [3, 1, 2],
result = array
.map((v, index) => ({ index, top: (children.indexOf(v) + 1) || Infinity }))
.sort((a, b) => a.top - b.top || a.index - b.index)
.map(({ index }) => array[index]);
console.log(result);
A faster way, could be the use of a Set
.
This works only for unique values.
var array = [6, 5, 4, 3, 2, 1],
children = [3, 1, 2],
result = Array.from(new Set([...children, ...array]));
console.log(result);
Use Arrays.sort()
and passing to it a custom comparator. Try the following:
let arrayParent = [6, 5, 4, 3, 2, 1];
let arrayChild = [3, 1, 2];
arrayParent.sort((a,b)=>{
var indexA = arrayChild.indexOf(a);
var indexB = arrayChild.indexOf(b);
if(indexA == -1 && indexB == -1){
return 0;
} else if(indexA == -1 || indexB == -1){
return indexA === -1 ? 1 : -1;
} else{
return indexA - indexB;
}
});
console.log(arrayParent);