4

I'm trying to filter an array of objects where the filter is another array (of integers) which are values of properties of the first array. I've managed to make it work but I'm not sure if it's the best way. Since I'm a beginner in javascript, I'd appreciate any suggestions/improvements.

The items.json file contains an object with an array of objects. I want to filter all the objects (within that array) that have an id equal to the "ids" on the itemsids array.

code:

const itemsall = require('./items.json');

let itemsids = [1, 403, 3];

let filtereditems = [];

itemsids.forEach(id => {
  itemsall.items.forEach(item => {
    if (id === item.id) {
      filtereditems.push(item);
    }
  });
});

items.json (a small part of it)

{
    "items": [
        {
            "id": 0,
            "name": "Egg",
            "img": "http://www.serebii.net/pokemongo/items/egg.png"
        },
        {
            "id": 1,
            "name": "Pokeball",
            "img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
        },
        {
            "id": 2,
            "name": "Greatball",
            "img": "http://www.serebii.net/pokemongo/items/greatball.png"
        }
   ]
}

output: (expected)

[
    {
        "id": 0,
        "name": "Egg",
        "img": "http://www.serebii.net/pokemongo/items/egg.png"
    },
    {
        "id": 403,
        "name": "Cool Incense",
        "img": "http://www.serebii.net/pokemongo/items/incense.png"
    },
    {
        "id": 3,
        "name": "Ultraball",
        "img": "http://www.serebii.net/pokemongo/items/ultraball.png"
    }
]

Thanks!

1 Answer 1

10

You can use filter() and indexOf() to return filtered array.

var data = {
  "items": [{
    "id": 0,
    "name": "Egg",
    "img": "http://www.serebii.net/pokemongo/items/egg.png"
  }, {
    "id": 1,
    "name": "Pokeball",
    "img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
  }, {
    "id": 2,
    "name": "Greatball",
    "img": "http://www.serebii.net/pokemongo/items/greatball.png"
  }]
}
let itemsids = [1, 403, 3];

var result = data.items.filter(function(e) {
  return itemsids.indexOf(e.id) != -1
})

console.log(result)

With ES6/ES7 you can use includes() like this.

var result = data.items.filter((e) => itemsids.includes(e.id));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ! I used the 2nd method (ES6/7) since its running server-side. Much more simple and clean.

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.