0

I received a big array of object from the backend and I used filtering to leave only these values

const markets = ['IT', 'DE', 'UK', 'FR', 'NL', 'US'] // so now this is what have

I am going then to map through markets, but it will always start by IT and follows that order. Is there a way to sort this following a specific order?

['US', 'DE', 'UK', 'FR', 'IT', 'NL']

I want to sort every array that i receive following this specific order even if I don't receive all the values.

David
  • 188,958
  • 33
  • 188
  • 262
Laugh Tale
  • 13
  • 3
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort ? (With your custom sorting logic, of course.) – David May 13 '22 at 13:59
  • Does this answer your question? [JavaScript : Sorting an array](https://stackoverflow.com/questions/45162860/javascript-sorting-an-array) – Kai-Sheng Yang May 13 '22 at 14:01
  • Sounds to me like you want to [sort an array based on another array](https://stackoverflow.com/questions/13304543/javascript-sort-array-based-on-another-array). – Alexander Nied May 13 '22 at 17:43

5 Answers5

1

One could implement a function which uses an object as lookup for each of a market's precedence value and which in addition places unknown market items last.

function getAssuredMarketPrecedence(marketList) {
  const marketPrecedence = {
    US: 0, DE: 1, UK: 2, FR: 3, IT: 4, NL: 5,
  };
  return Array
    .from(marketList)
    .sort((a, b) =>
      (marketPrecedence[a] ?? 1000)  - (marketPrecedence[b] ?? 1000)
    );
}
const markets = ['IT', 'DE', 'unknown2', 'UK', 'FR', 'unknown1', 'NL', 'US']
const sorted = getAssuredMarketPrecedence(markets);

console.log({ markets, sorted });
.as-console-wrapper { min-height: 100%!important; top: 0; }
Peter Seliger
  • 8,830
  • 2
  • 27
  • 33
0

You need to write your own custom compare function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Smth like this:

markets = ['IT', 'DE', 'UK', 'FR', 'NL', 'US']

markets.sort((item1, item2) => {
    neededOrder = ['US', 'DE', 'UK', 'FR', 'IT', 'NL']
    idx1 = neededOrder.indexOf(item1)
    idx2 = neededOrder.indexOf(item2)
    if(idx1 < idx2) {
        return -1
    }
    else if(idx1 > idx2) {
        return 1
    } else {
        return 0
    }
})
random322
  • 26
  • 1
0

You can assign each market a value within an object, and use that to compare and sort against the market array you receive from the backend:

const markets = ['IT', 'DE', 'UK', 'FR', 'NL', 'US']

let mappedMarkets = {
  'US': 1,
  'DE': 2,
  'UK': 3,
  'FR': 4,
  'IT': 5,
  'NL': 6
}

console.log(markets.sort((a, b) => mappedMarkets[a] - mappedMarkets[b]))
Marco
  • 506
  • 5
  • 15
  • 1
    @RamiBenAbdallah ... not knowing the exact requirements, the above approach would fail to sort markets with unknown market items like e.g. `const markets = ['IT', 'DE', 'unknwon2', 'UK', 'FR', 'unknwon1', 'NL', 'US']`. This is not an issue as long as there are always just market items in an array which have a mapped counterpart. – Peter Seliger May 13 '22 at 14:59
0

You can:

  • Break the list into two sub-arrays
  • Those on the order list which you can sort in the desired order
  • Those not on the list which you do not have to sort
  • Combine the sub-arrays using: [...s1, ...s2]

const markets = ['IT', 'DE', 'UK', 'FR', 'NL', 'US','KE','UG','TZ'], // so now this is what have
      order = ['US', 'DE', 'UK', 'FR', 'IT', 'NL'],
      
      output = [
          ...markets.filter(c => order.includes(c)).sort(
              (a, b) =>
              order.findIndex(x => x === a) - order.findIndex(x => x === b)
          ),
          ...markets.filter(c => !order.includes(c))
      ];
      
      
console.log( output );

Alternatively, ...

If each markets only includes items that are in order you can just leave out the second sub-array and use the following instead:

const markets = ['IT', 'DE', 'UK', 'NL', 'US'], 
      order = ['US', 'DE', 'UK', 'FR', 'IT', 'NL'],
      
      output = markets.filter(c => order.includes(c)).sort(
          (a, b) =>
          order.findIndex(x => x === a) - order.findIndex(x => x === b)
      );
      
      
console.log( output );
PeterKA
  • 22,910
  • 4
  • 23
  • 48
-2

I am afraid there is no such way, it should be ascending or descending. Or if it is not that much data, you can sort that manually.

Alazar-dev
  • 17
  • 1
  • 5
  • i can't sort it manually since everytime it sends values in different order – Laugh Tale May 13 '22 at 14:04
  • Yeah, that's just additional info, you can't do that in this case. – Alazar-dev May 13 '22 at 14:06
  • @Alazar-dev please use comment section for this kind of reply – Sumit Sharma May 13 '22 at 14:11
  • @Alazar-dev: Well, the OP *can* sort the array. They just need to define the sorting logic. Which we don't know. – David May 13 '22 at 14:12
  • @David: the sorting should always be this ways ['US', 'DE', 'UK', 'FR', 'IT', 'NL'] if i don't receive 'UK' for exemple, it should look like this ['US', 'DE', 'FR', 'IT', 'NL'] – Laugh Tale May 13 '22 at 14:14
  • @RamiBenAbdallah: If the result should *always* be that *exact* array then just hard-code that array. But surely that's not what you meant. If you want to sort an array, JavaScript [provides a mechanism for that](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). Specifically take a look at the examples which provide a comparer function. You need to write that function. Within that function you would define the logic on how to determine if any two elements of the array are sorted relative to each other. – David May 13 '22 at 14:17
  • @David: yes that i was trying to do, can you give me a quick exemple on how the function would look like and thank you – Laugh Tale May 13 '22 at 14:19
  • @RamiBenAbdallah: You can find examples and documentation of what a sort comparer looks like and how it works [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). You can also try [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) and [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). (You may be noticing a pattern by now.) You are encouraged to make an attempt to write your code. – David May 13 '22 at 14:21