arrays - 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.
解决方案
let newArray = [];
state.forEach(({productNumber}) => {
if (array.indexOf(productNumber) === -1) {
newArray = [...newArray, productNumber];
}
})
或者类似地,您可以过滤状态数组并返回 productNumber 不在您的第二个数组中的产品。
const newArray = state.filter(({productNumber}) => array.indexOf(productNumber) === -1);
推荐阅读
- spring - @Autowired Bean 返回 null
- nativescript - 导航到尚未使用的框架
- python - 如何取这两个不同形状数组的点积?
- dynamics-crm - PowerApps - 为 CRM 中的约会“设置相关”
- spring-boot - spring boot docker应用我们应该怎么做nginx反向代理配置呢?
- javascript - Material UI 如何为子组件设置外部样式,整个组件使用一种主要的通用样式
- javascript - 如何在 Vue.js 或 Nuxt.js 中的 First Contentful Paint 或第一个元素之后加载组件?
- html - HTML 对象 VBA
- python - 在具有初始条件的连续块上过滤后重新采样(以避免不连续性)
- bokeh - 将 HoloViews 绘图与 Bokeh 自定义链接