最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Sorting a Array of Object based on the value of another array - Stack Overflow

matteradmin7PV0评论

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
})

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:

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';

Share Improve this question asked Nov 16, 2024 at 22:08 Powl_LondonPowl_London 192 bronze badges 1
  • newIndexes = [1,2,3,7,4,8,5,9,6,10); has a syntax error and is not properly defined. Consider const newIndexes = [1,2,3,7,4,8,5,9,6,10]; instead – Mark Schultheiss Commented Nov 16, 2024 at 22:21
Add a comment  | 

4 Answers 4

Reset to default 0

You could group by pos and then map by pos as well.

const
    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],
    temp = Object.groupBy(driverArray, ({ pos }) => pos),
    result = newIndexes.map(pos => temp[pos].shift());

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Basicaly, for each position you need to find the matching item. So first we make a dictionary object from each pos to its item. It would be more efficient.

const 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]; 

// first to make efficient perpare dictionary
const dict = driverArray.reduce(function(agg, item) {
  agg[""+item.pos] = item;
  return agg
}, {})

// now let's create sorted array
const result = newIndexes.map(function(pos) {
  return dict[""+pos]
})

console.log(result)
.as-console-wrapper { min-height: 100%; }

Another solution would be to create an idx lookup dictionary and then use that to establish the desired order.

const
    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],
    idx = Object.fromEntries(driverArray.map((e,i)=>[e.pos,i])),
    res = newIndexes.map(p=>driverArray[idx[p]]);

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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);

Post a comment

comment list (0)

  1. No comments so far