Boky
Boky

Reputation: 12084

Map and filter functions in javascript

I have an array as follows :

let allCars = [
    {
        id: 1,
        listID: 2,
        name: "CAR 1",
        url: "Fixed 2016-W24"        
    }, {
        id: 2,
        listID: 2,
        name: "CAR 2",
        url: "Fixed 2016-W24"        
    }, {
        id: 3,
        listID: 3,
        name: "CAR 3",
        url: "Fixed 2016-W24"       
    },{
        id: 1,
        listID: 1,
        name: "CAR 4",
        url: "Fixed 2016-W24"        
    },{
        id: 5,
        listID: 2,
        name: "CAR 5",
        url: "Fixed 2016-W24"        
    }
];

and I have also an array of cars which are in the card, something like this :

let cardContent = [
    {
    carID: 1,
    listID: 2
  },
  {
    carID: 5,
    listID: 2
  }
]

I'm trying to get cars with id=1, listID=2 and with id=5, listID=2 from allCars.

I tried to map through cardContent and then filter only those with that carID and list ID from allCars. But without success.

I tried something like this

const result = allCars.map(i => {
    return {
    carID: i.carID,
    listID: i.listID
  }
}).filter(a => {
    return ((a.carID === cardContent.carID) && (a.listID === cardContent.listID))
});

Here is jsfiddle.

Any advice?

Upvotes: 1

Views: 93

Answers (2)

Nicholas Robinson
Nicholas Robinson

Reputation: 1429

Try this:

let allCars = [
    {
        id: 1,
        listID: 2,
        name: "CAR 1",
        url: "Fixed 2016-W24"        
    }, {
        id: 2,
        listID: 2,
        name: "CAR 2",
        url: "Fixed 2016-W24"        
    }, {
        id: 3,
        listID: 3,
        name: "CAR 3",
        url: "Fixed 2016-W24"       
    },{
        id: 1,
        listID: 1,
        name: "CAR 4",
        url: "Fixed 2016-W24"        
    },{
        id: 5,
        listID: 2,
        name: "CAR 5",
        url: "Fixed 2016-W24"        
    }
];

let cardContent = [
    {
    carID: 1,
    listID: 2
  },
  {
    carID: 5,
    listID: 2
  }
]

const output = allCars.filter(car => cardContent.some(card => (car.id === card.carID && car.listID === card.listID)));

console.log(output);

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122125

You could do this with Array#filter and Array#some

let allCars = [{"id":1,"listID":2,"name":"CAR 1","url":"Fixed 2016-W24"},{"id":2,"listID":2,"name":"CAR 2","url":"Fixed 2016-W24"},{"id":3,"listID":3,"name":"CAR 3","url":"Fixed 2016-W24"},{"id":1,"listID":1,"name":"CAR 4","url":"Fixed 2016-W24"},{"id":5,"listID":2,"name":"CAR 5","url":"Fixed 2016-W24"}];
let cardContent = [{"carID":1,"listID":2},{"carID":5,"listID":2}]

const result = allCars.filter(function(e) {
  return cardContent.some(function(a) {
    return e.id == a.carID && e.listID == a.listID;
  })
})

console.log(result);

Upvotes: 1

Related Questions