1

Here's an array of book objects.

const books=[
    {
      "id": 1,
      "title": "NPR",
      "url": "https://www.npr.org"
    },
    {
      "id": 2,
      "title": "Google Docs",
      "url": "https://docs.google.com/"
    },
    {
      "title": "Fetch API Docs",
      "url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",
      "id": 3
    },
    {
      "title": "Yahoo",
      "url": "http://www.yahoo.com",
      "id": 4
    },
    {
      "title": "Google",
      "url": "http://www.google.com",
      "id": 5
    }
  ]

And a separate array of IDs

const selectedIds = [1, 5, 3]

With javascript, how can I filter the books array to just the selectedIds (keeping the same order as in selectedIds)?

Final result I'm looking to get:

selectedBooks = [
    {
      "id": 1,
      "title": "NPR",
      "url": "https://www.npr.org"
    },
    {
      "title": "Google",
      "url": "http://www.google.com",
      "id": 5
    },
    {
      "title": "Fetch API Docs",
      "url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",
      "id": 3
    }
  ]

My current code is like this but this preserves the order of the books array (i.e. [1, 3, 5]):

books.filter(function(item) {
   return selectedIds.includes(item.id);
}
1
  • You sure you got the incorrect result. I tested your code on Chromium 77.0.3865.90 and Firefox Quantum 69.0.1 (64-bit) and they seemed to give out the correct order. I can only assume that your const selectedIds's order could be changed to 1, 3, 5 to ensure order preservation. NVM that, I read too quickly, you wanted to keep the order of selectedIDs. :) Commented Oct 7, 2019 at 20:01

2 Answers 2

3

Go in the other direction.

 selectedIds.map(id => books.find(b => b.id === id))
Sign up to request clarification or add additional context in comments.

Comments

1

const books = [{
    id: 1,
    title: "NPR",
    url: "https://www.npr.org"
  },
  {
    id: 2,
    title: "Google Docs",
    url: "https://docs.google.com/"
  },
  {
    title: "Fetch API Docs",
    url: "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",
    id: 3
  },
  {
    title: "Yahoo",
    url: "http://www.yahoo.com",
    id: 4
  },
  {
    title: "Google",
    url: "http://www.google.com",
    id: 5
  }
];

const selectedIds = [1, 5, 3];

const mapped = selectedIds.map(id => {
  return books.find(book => book.id === id);
});

console.log(mapped);

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.