Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting a Array of Object based on the value of another array

I have a basic array of objects that I want to reorder based on the value of another array.

This is something similar to what I want to do but is based purely on an array

items = [
    ['Anne', 'a'],
    ['Bob', 'b'],
    ['Henry', 'b'],
    ['Andrew', 'd'],
    ['Jason', 'c'],
    ['Thomas', 'b']
]

/* This works fine */
sorting = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
result = [];

sorting.forEach(function(key) {
    var found = false;
    items = items.filter(function(item) {
        if(!found && item[1] == key) {
            result.push(item);
            found = true;
            return false;
        } else
            return true;
    })
})

result.forEach(function(item) {
    console.log(item[0]) /// Bob Jason Henry Thomas Andrew
})

The code I have is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

driverArray = [
   {label: "Driver 1",  pos: 1},
   {label: "Driver 2",  pos: 2},
   {label: "Driver 3",  pos: 3},
   {label: "Driver 4",  pos: 4},
   {label: "Driver 5",  pos: 5},
   {label: "Driver 6",  pos: 6},
   {label: "Driver 7",  pos: 7},
   {label: "Driver 8",  pos: 8},
   {label: "Driver 9",  pos: 9},
   {label: "Driver 10", pos:10}
];

newIndexes = [1,2,3,7,4,8,5,9,6,10); // These match the pos key;

I then want to sort the driverArray in the order of the newIndexes array. The newIndexes array match the Object Key ‘pos’;

>Solution :

This can be pretty simple just match the pos to the value in the other array and map to that.

let driverArray = [
   {label: "Driver 1",  pos: 1},
   {label: "Driver 2",  pos: 2},
   {label: "Driver 3",  pos: 3},
   {label: "Driver 4",  pos: 4},
   {label: "Driver 5",  pos: 5},
   {label: "Driver 6",  pos: 6},
   {label: "Driver 7",  pos: 7},
   {label: "Driver 8",  pos: 8},
   {label: "Driver 9",  pos: 9},
   {label: "Driver 10", pos:10}
];

const newIndexes = [1,2,3,7,4,8,5,9,6,10]; 
const driverArrayOrdered = newIndexes.map(ni=> driverArray.find(x=>x.pos===ni));

console.log("Sorted:",driverArrayOrdered);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading