1

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?

2 Answers 2

1

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

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

Comments

0

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

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.