0

Hi I would like to map over an array and sort it depending on an lookup object.

const obj = {
  "email": {position: 1, name: "email"},
  "firstname": {position: 2, name: "firstname"},
  "lastname": {position: 3, name: "lastname"}
}

const arr = ["lastname", "email", "firstname"];

expected output: ["email", "firstname", "lastname"];

I know that I must use the map function in order to return a new array. I can get an new array with the full or object or retrieving only a array with all names or position properties. But I cannot figure out how to sort them.

Thanks for your help

1 Answer 1

5

Array.sort function accepts a callback (sorter) function that will return comparison of any two items in array. So just need to compare their position (of 2 items in array). This is done by substracting them to get a positive/0/negative result.

const obj = {
  "email": {position: 1, name: "email"},
  "firstname": {position: 2, name: "firstname"},
  "lastname": {position: 3, name: "lastname"}
}

const arr = ["lastname", "email", "firstname"];

// expected output: ["email", "firstname", "lastname"];
arr.sort(function(a,b) {
  return obj[a].position - obj[b].position
})

console.log(arr)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.