Boky Boky - 4 months ago 11
Javascript Question

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?

Answer

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