0

I am trying to sort out the array based on the specific order. The data itself will include fruits, prices, etc. I am struggling to make a sort() function to arrange the order.

fruit = ["Banana", "Orange", "Apple", "Pear"];
const data = storeData.filter(...);

// sort the data
data.sort((a, b) => (a.fruit > b.fruit ? 1 : -1));   // output: apple, banana, orange, pear

I expect the result to be banana, orange, pear, apple instead of apple, banana, orange, pear or banana, orange, apple, pear. I am still learning more. Thank you!

By the way, I am using Reactjs or javascript-based platform.

  • Hey. welcome to SOF. could you please elaborate on your question? I couldn't understand what you really want. – Mahdi Ghajary Mar 24 '20 at 15:04
  • Does this answer your question? [Javascript - sort array based on another array](https://stackoverflow.com/questions/13304543/javascript-sort-array-based-on-another-array) – User863 Mar 24 '20 at 15:05
  • @mahdi Thank you for a warm welcome. I am trying to find a way to sort the data by grouping by fruits: Banana > Orange > Pear > Apple. The data that's called by API was not sorted, so I want to make a sort() function to put the fruits in the same order based on another array. Before sort() - `Banana, Orange, Apple, Pear` After sort() - `Banana, Orange, Pear, Apple` – femaleProgrammer1964 Mar 24 '20 at 15:13
  • @femaleProgrammer1964 `fruit.sort(function(a, b){ return defaultOrder.indexOf(a) - defaultOrder.indexOf(b); });` check this. – Mahdi Ghajary Mar 24 '20 at 15:15
  • @mahdi Your contribution is helpful. It is similar to Bhavik's answer, but you both are correct. Thanks so much! – femaleProgrammer1964 Mar 24 '20 at 15:31

2 Answers2

0

Here's the one of the possible option:

Let say, you need to filter fruit without filtering anything, you can use the below:

fruit.sort((a,b) => defaultOrder.i(a) > defaultOrder.indexOf(b) ? 1 : (-1));

In case if you need to use filtered data, please change fruit.sort to data.sort like;

data.sort((a,b) => defaultOrder.indexOf(a) > defaultOrder.indexOf(b) ? 1 : (-1));

if you want to chain the methods, here's the way

fruit
.filter(a => a !== 'Banana')
.sort((a,b) => 
defaultOrder.indexOf(a) > defaultOrder.indexOf(b) ? 1 : (-1));

if you have an object array, you can go for the following:

fruit.sort((x,y) => defaultOrder.findIndex(a => a == x.fruit  ) > defaultOrder.findIndex(b => b == y.fruit) ? 1 : (-1));

hope this helps.

Bhavik

Bhavik
  • 124
  • 3
0

Check this:

fruit.sort( (itemA , itemB) => defaultOrder.indexOf(itemA) - defaultOrder.indexOf(itemB)); 
Mahdi Ghajary
  • 2,717
  • 15
  • 20