首页 > 解决方案 > I need to compare two arrays/state and get the data from the first array/state that doesn't match with the data on the second array - Reactjs

问题描述

So I'm working with states in React, and i want to compare the two arrays/state and get the data from the first array that doesn't match with the data on the second array. The first array is a state, and the second one is an array. My first state/array looks like this = state : [ { id : id , productNumber : "productnumber"}... ] and the second array loos like this = array ["productnumber","productnumber"...], and here what is my code's look like.

let newArray = [];

state.forEach(product=>{
    array.forEach(productNumber=>{
        if(product.productNumber !== productNumber){
            newArray = [...newArray,product.productNumber];
        }
    })
})

and it doesn't work, it stores all the data from the first array/state and even doubled it. I tried using nested if statements, still doesn't. I don't know what todo.

标签: arraysreactjsstate

解决方案


let newArray = [];

state.forEach(({productNumber}) => {
  if (array.indexOf(productNumber) === -1) {
    newArray = [...newArray, productNumber];
  }
})

或者类似地,您可以过滤状态数组并返回 productNumber 不在您的第二个数组中的产品。

const newArray = state.filter(({productNumber}) => array.indexOf(productNumber) === -1);

推荐阅读