Home:ALL Converter>Sorting an object by attribute, by an array with that attribute

Sorting an object by attribute, by an array with that attribute

Ask Time:2017-09-07T17:24:35         Author:Idan Elhalwani

Json Formatter

I need to order an array of objects by its "ID" property, the array looks something like this:

var data = [
    {
        id: 1,
        name: "Test"
    },
    {
        id: 2,
        name: "Another test"
    },
    {
        id: 3,
        name: "Third test"
    }
];

and the 'sorting' array looks like this:

var sortingArray = [2,3,1];

How do I go about sorting the object array by the sorting array?

Author:Idan Elhalwani,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/46092670/sorting-an-object-by-attribute-by-an-array-with-that-attribute
Hassan Imam :

You can use array#reduce and array#filter\n\n\r\n\r\nconst data = [{id: 1,name: \"Test\"},{id: 2,name: \"Another test\"},{id: 3,name: \"Third test\"}], \r\n sortingArray = [2,3,1];\r\n\r\nvar result = sortingArray.reduce((res, n) => {\r\n let temp = data.filter(o => o.id === n);\r\n return res.concat(temp);\r\n},[]);\r\n\r\nconsole.log(result);",
2017-09-07T09:29:43
mbehzad :

const sortedData = sortingArray.map(id => data.find(val => val.id === id))\n",
2017-09-07T09:27:42
Stuart :

You'll need a small function, something like:\n\nfunction sortByKey(array, key) \n{\n return array.sort(function(a, b) {\n let x = a[key]; var y = b[key];\n return ((x < y) ? -1 : ((x > y) ? 1 : 0));\n });\n}\n\n\nand use it like:\n\nlet sorted = sortByKey(data, \"id\");\n",
2017-09-07T09:27:26
yy