0

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]];
0

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.