1

I have the following problem in my ReactJs application. Let's say I have two arrays like this:

var cart = [
   {id: 1, name: "item1"}, 
   {id: 2, name: "item2"}, 
];
var productsArr = [
   {proId: 1, category: 'cat1'}, 
   {proId: 5, category: 'cat7'}, 
];

Is it possible to compare these 2 arrays and find any objects in productsArr which cart's id quals productsArr's proId and remove that object from only productsArr?

(If so, as I explained in this example, productsArr[0] should be removed.)

Thanks in advance.

1
  • 1
    Yep, it's possible. Where are you stuck in your code attempt so far? Commented Aug 26, 2021 at 14:30

2 Answers 2

7

You can use Array#filter in conjunction with Array#some.

var cart = [
   {id: 1, name: "item1"}, 
   {id: 2, name: "item2"}, 
];
var productsArr = [
   {proId: 1, category: 'cat1'}, 
   {proId: 5, category: 'cat7'}, 
];
productsArr = productsArr.filter(({proId})=>!cart.some(({id})=>proId === id));
console.log(productsArr);

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

Comments

2

var cart = [
   {id: 1, name: "item1"}, 
   {id: 2, name: "item2"}, 
];

var productsArr = [
   {proId: 1, category: 'cat1'}, 
   {proId: 5, category: 'cat7'}, 
];


for (var i = 0; i<productsArr.length; i++) {
    if (cart.find(item => item.id === productsArr[i].proId)) {
        productsArr.splice(i,1);
        i--;
    }
}

console.log(productsArr);

3 Comments

Taking into account react.js tag, I would assume, productsArr is a part of some component's state, hence immutable approach most likely would be preferred, whereas Array.prototype.splice() would mutate original array.
@YevgenGorbunkov totally makes sense, I didn't pay attention to the tags
No worries. You may overcome that, though, by shallow copying initial array, e.g. const _productsArr = [...productsArr] and then _productsArr.splice(i,1).

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.