1

I have an array that looks like this:

cPrefs = [0:{ id: 5, name: "Sixth thing" },
 1:{ id: 3, name: "Fourth thing" },
 2:{ id: 4, name: "Fifth thing" },
 3:{ id: 0, name: "First thing" },
 4:{ id: 2, name: "Third thing" },
 5:{ id: 1, name: "Second thing" }]

And I have another sorting array that looks like this:

cOrder = ["1", "3", "2", "5"]

I need to sort the first array by the second (which has ids) and leave the non identified objects at the end (in any order). So a correct final sorting could look like this:

[0:{ id: 1, name: "Second thing" },
 1:{ id: 3, name: "Fourth thing" },
 2:{ id: 2, name: "Third thing" },
 3:{ id: 5, name: "Sixth thing" },
 4:{ id: 0, name: "First thing" },
 5:{ id: 4, name: "Fifth thing" }]

I am not sure of the best way to accomplish this. I have tried

const output = cOrder.map(i => cPrefs[i].id)

but it throws out my other values, and I suppose I could loop through and rebuild the array, but I was curious if there was a more efficient way.

Stephen
  • 8,038
  • 6
  • 41
  • 59
  • have you thought about `sort()` instead of `map()` ? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Calvin Nunes Nov 11 '19 at 12:25
  • 1
    Possible Duplicate of [Sort array containing objects based on another array](https://stackoverflow.com/questions/13518343/sort-array-containing-objects-based-on-another-array) – Calvin Nunes Nov 11 '19 at 12:26
  • This question misses the _multidimensional_ part – Andreas Nov 11 '19 at 12:29

1 Answers1

0

You could take an object for the sort order and move unknown id to the end with a default value Infinity.

var cPrefs = [{ id: 5, name: "Sixth thing" }, { id: 3, name: "Fourth thing" }, { id: 4, name: "Fifth thing" }, { id: 0, name: "First thing" }, { id: 2, name: "Third thing" }, { id: 1, name: "Second thing" }],
     cOrder = [1, 3, 2, 5],
     order = cOrder.reduce((r, k, i) => (r[k] = i + 1, r), {});

cPrefs.sort((a, b) => (order[a.id] || Infinity) - (order[b.id] || Infinity));

console.log(cPrefs);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392