1

I tried this as known

 test.sort(function (a, b) {
    var textA = a[0].Val1;
    var textB = b[0].Val1;
    if (textA > textB)
        return -1;
    if (textA < textB)
        return 1;
    return 0;
});

but I want to see my sorted array like this

{name: 'John', Val1: 4, hireDate: "July 1, 2010"},
{name: 'XXX', Val1: 4, hireDate: "August 15, 2009"},
{name: 'YYY', Val1: 2, hireDate: "August 15, 2009"},
{name: 'ZZZ', Val1: 2, hireDate: "August 15, 2009"},
{name: 'ZZZ', Val1: 16, hireDate: "August 15, 2009"},
{name: 'ZZZ', Val1: 16, hireDate: "August 15, 2009"},
{name: 'Ana', Val1: 1, hireDate: "December 12, 2011"}

2 Answers2

0

You can define the order in a separate scores list, and use .indexOf as follows:

const test = [
  {name: 'John', Val1: 4, hireDate: "July 1, 2010"},
  {name: 'XXX', Val1: 4, hireDate: "August 15, 2009"},
  {name: 'YYY', Val1: 2, hireDate: "August 15, 2009"},
  {name: 'ZZZ', Val1: 2, hireDate: "August 15, 2009"},
  {name: 'ZZZ', Val1: 16, hireDate: "August 15, 2009"},
  {name: 'ZZZ', Val1: 16, hireDate: "August 15, 2009"},
  {name: 'Ana', Val1: 1, hireDate: "December 12, 2011"}
];
const scores = [4,2,16];
const MAX = scores.length;

const sorted = test.sort((a, b) => {

  let indexOfA = scores.indexOf(a.Val1);
  indexOfA = (indexOfA >= 0) ? indexOfA : MAX;
  
  let indexOfB = scores.indexOf(b.Val1);
  indexOfB = (indexOfB >= 0) ? indexOfB : MAX;
  
  return indexOfA - indexOfB;
});

console.log(sorted);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • The OP didn't really word the question very well, he's basically wanting to sort by `Val1` in text ordering descending.. – Keith Jan 13 '21 at 13:37
0

You can do it by creating an ordering object.

const data = [
  { name: 'John', Val1: 4, hireDate: 'July 1, 2010' },
  { name: 'XXX', Val1: 4, hireDate: 'August 15, 2009' },
  { name: 'YYY', Val1: 2, hireDate: 'August 15, 2009' },
  { name: 'ZZZ', Val1: 2, hireDate: 'August 15, 2009' },
  { name: 'ZZZ', Val1: 16, hireDate: 'August 15, 2009' },
  { name: 'ZZZ', Val1: 16, hireDate: 'August 15, 2009' },
  { name: 'Ana', Val1: 1, hireDate: 'December 12, 2011' },
];

const order = { 4: 1, 2: 2, 16: 3 };
data.sort(
  (x, y) =>
    (order[x.Val1] || Number.MAX_VALUE) - (order[y.Val1] || Number.MAX_VALUE)
);
console.log(data);
mr hr
  • 3,162
  • 2
  • 9
  • 19