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.

3

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.