Reputation: 4286
The following function re-orders an array based on the declared sortOrder
.
const originalArray = ['Apple', 'Cat', 'Fan', 'Goat', 'Van', 'Zebra'];
const sortOrder = ['Zebra', 'Van'];
const sorter = (a, b) => {
if(sortOrder.includes(a)){
return -1;
};
if(sortOrder.includes(b)){
return 1;
};
return 0;
};
originalArray.sort(sorter);
console.log(originalArray);
How can do correctly compare 2d arrays, given the following:
const originalArray = [['Apple',1], ['Cat',2], ['Fan',3], ['Goat',4], ['Van',5], ['Zebra',6]];
const sortOrder = [['Zebra',7], ['Van',8]];
Upvotes: 0
Views: 23
Reputation: 4337
I used the Array.some
method.
It returns true
if any time the argument function's executed and it returns true
Therefore, if my argument function in the Array.some
method asks for a comparison in the string value parts of the 2d array(array[index][0]
) that means it would work JUST LIKE includes for what you have :D
const originalArray = [['Apple',1], ['Cat',2], ['Fan',3], ['Goat',4], ['Van',5], ['Zebra',6]];
const sortOrder = [['Zebra',7], ['Van',8]];
const sorter = (a, b) => {
//the has function would return true if only ONCE the originalArray[index][0]==sortOrder[someIndex][0]
function has(x){return sortOrder.some(e=>e[0]==x[0])}
if(has(a)){
return -1;
};
if(has(b)){
return 1;
};
return 0;
};
originalArray.sort(sorter);
console.log(originalArray);
Upvotes: 1