Bhushan Patil
Bhushan Patil

Reputation: 125

Sort an array using another array in strictly same order typescript

I am trying to sort this array

const originalArray = ['Apple', 'Cat', 'Fan', 'Zebra', 'Goat', 'Van'];

using this array

const sortOrder = ['Zebra', 'Van', "Cat"];

I have tried to use this method;

const sortedArray = originalArray.sort((a, b) => {
  return sortOrder.indexOf(b) - sortOrder.indexOf(a);
});

console.log(sortedArray) // Output:["Cat","Van","Zebra","Apple","Fan","Goat"]

Although this is not the expected result

The expected Output should be like this

["Zebra","Van","Cat","Apple","Fan","Goat"]

Open to any solution using any library as well like lodash. Thanks in advance

Upvotes: 1

Views: 1583

Answers (2)

Rick Su
Rick Su

Reputation: 16440

Try sort it with reverse of sortOrder

const originalArray = ['Apple', 'Cat', 'Fan', 'Zebra', 'Goat', 'Van'];
const sortOrder = ['Zebra', 'Van', "Cat"];

// reverse the `sortOrder`
let reverseOrder = sortOrder.reverse();

// if you want to keep `sortOrder` as it is
// then do slice() and then reverse()
// let reverseOrder = sortOrder.slice().reverse();

// The key point here is to sort by reverse of `sortOrder`
let sortedArray = originalArray.sort((a, b) => {
  return reverseOrder.indexOf(b) - reverseOrder.indexOf(a);
})

console.log(sortedArray)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

You could take an object with the order and for not known items take a large value to sort them to the end of the array

const
    array = ['Apple', 'Cat', 'Fan', 'Zebra', 'Goat', 'Van'],
    sortOrder = ['Zebra', 'Van', "Cat"],
    order = Object.fromEntries(sortOrder.map((k, i) => [k, i + 1]));

array.sort((a, b) =>
    (order[a] || Number.MAX_VALUE) - (order[b] || Number.MAX_VALUE)
);

console.log(array);

Upvotes: 1

Related Questions