-2

I'm trying to sort a JSON list from another list, by a Value in the JSON list.

var jsonList = [{'id': 'das', 'name': 'something'}, {'id': 'rtn', 'name': 'Something Else'}, {'id': 'ddsn', 'name': 'Something ElseElse'}];

var orderList = ['rtn', 'ddsn', 'das'];

var goodList = someFunction(jsonList, orderList);

I need the output to be it sorted from the orderList by the id in the json list.

goodList = [{'id': 'rtn', 'name': 'Something Else'}, {'id': 'ddsn', 'name': 'Something ElseElse'}, {'id': 'das', 'name': 'something'}]

I asked the same question for python, but now I need it in JavaScript.

Dug
  • 75
  • 1
  • 4

1 Answers1

-1

JS can also sort with a custom comparator:

const jsonList = [{'id': 'das', 'name': 'something'}, {'id': 'rtn', 'name': 'Something Else'}, {'id': 'ddsn', 'name': 'Something ElseElse'}];

const orderList = ['rtn', 'ddsn', 'das'];
jsonList.sort((a, b) => orderList.indexOf(a.id) - orderList.indexOf(b.id));
console.log(jsonList);
Aplet123
  • 33,825
  • 1
  • 29
  • 55