-1

I'm trying to sort an array of string in an angular application that for example contains :

names = ["Eve","Jhon","Maria","Jadon"] and I want to sort them in this order : ["Maria", "Eve", "Jadon", "Jhon"] I tried

names.sort(); 

But this will order it into an ascending order but for me I want to choose the order as I want it to be ! as if I have a table and I want to sort it's header's items=["id","name","email","fullname","tel"] to ["name","id","email","tel","fullname"].

Do you have any idea?

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
SS_FStuck
  • 231
  • 1
  • 5
  • 20

2 Answers2

1

Here's an example how you can create custom sorter function to sort by predefined ordered array

const THIS_ORDER = ["Maria", "Eve", "Jadon", "Jhon"] 

const data = ["Eve","Jhon","Maria","Jadon"];

const sorter = (a, b) => THIS_ORDER.indexOf(a) - THIS_ORDER.indexOf(b)

const result = data.sort(sorter)

console.log(result)
Teneff
  • 30,564
  • 13
  • 72
  • 103
1

You can use this,

  const arrToSort = ["Eve","Jhon","Maria","Jadon"]
  
  const priority = ["Maria", "Eve", "Jadon", "Jhon"];

  const sortedObj = arrToSort.sort((a, b) => {
    const indexOfA = priority.indexOf(a);
    const indexOfB = priority.indexOf(b);
    if (indexOfA < indexOfB) return -1;
    if (indexOfA > indexOfB) return 1;
    return 0;
  });

  console.log(sortedObj);
Alish Giri
  • 1,855
  • 18
  • 21