[英]Getting Values from comparing Two Arrays
I have two array one is the state like this我有两个数组一个是 state 像这样
const [state,setState] = useState([])
and the another one is am getting from a form when it is submitted;另一个是在提交时从表单中获取;
ids = [4,5,6]
setState(ids)
Now, when i update the state second time the values are there ie 4,5,6 in the state.现在,当我第二次更新 state 时,值在 state 中有 4、5、6。 so the values are getting duplicated ie 4,5,6,4,5,6所以值被重复,即 4,5,6,4,5,6
What i want is to make sure that only the elements which is not present in the array gets pushed not all,and i get the valid output like following.我想要的是确保只有数组中不存在的元素被推送而不是全部,并且我得到有效的 output 如下所示。
4,5,6,7
If 7 is added.如果加了 7。
What i did is like this, which is totally wrong我所做的就是这样,这是完全错误的
const filterss = [...state];
setState([]);
filterss.push(values);
setState(filterss);
const filters = [...state];
values.forEach(item => {
if (filters.indexOf(item) < 0) {
filters.push(item);
}
})
setState(filters);
const ids=[4,5,6] let formSubmitIds=[4,5,6,7] let uniquieIds=[...new Set([...ids,...formSubmitIds])] console.log(uniquieIds)
Simply use this logic to setState accordingly ie setState(uniquieIds)
只需使用此逻辑相应地设置状态,即setState(uniquieIds)
ids are the stored values in state ids是 state 中存储的值
formSubmitIds is the new array which you are getting on submit of form formSubmitIds是您在提交表单时获得的新数组
[...ids,...formSubmitIds]
will merge both arrays [...ids,...formSubmitIds]
将合并 arrays
Set is used to remove duplicates Set用于删除重复项
[......new Set]
will convert Set back to an array with unique ids only [......new Set]
将 Set 转换回仅具有唯一 ID 的数组
First push all the old and new values in a single array then try using Set() to get unique values in the array.首先将所有旧值和新值推送到单个数组中,然后尝试使用 Set() 获取数组中的唯一值。 Here's the code.这是代码。
setState(new Set(arrayName))
Use Set()
constructor to achieve your goal.使用Set()
构造函数来实现您的目标。
Try:尝试:
const [state, setState] = useState([])
const ids = [4,5,6]
const formSubmittedIds = [4,5,6,7]
setState([...new Set([...ids, ...formSubmittedIds])]) // Sets [4, 5, 6, 7] to the state
Happy coding:)快乐编码:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.