如果两个值都不存在,我如何推入数组?这是我的数组:
[
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
如果我试图再次推入数组的名字:“tom”或文本:“tasty”,我不希望发生任何事情…但如果这两个都不存在那么我就输入。push()
我该怎么做呢?
这里你有一种方法可以在一行中为两个数组做这件事:
const startArray = [1,2,3,4]
const newArray = [4,5,6]
const result = [...startArray, ...newArray.filter(a => !startArray.includes(a))]
console.log(result);
//Result: [1,2,3,4,5,6]
推送后删除重复项
如果你已经有一个包含重复项的数组,将对象数组转换为字符串数组,然后使用Set()函数消除重复项:
let arr_obj = [
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
let arr_str = arr_obj.map(JSON.stringify)
let arr_unique = [...new Set(arr_str)].map(JSON.parse)
推前检查
如果你到目前为止没有重复的元素,你想在推入一个新元素之前检查重复:
let arr_obj = [
{ name: "tom", text: "tasty" },
{ name: "tim", text: "tusty" }
]
let new_obj = { name: "tom", text: "tasty" }
let arr_str = arr_obj.map(JSON.stringify)
!arr_str.includes(JSON.stringify(new_obj)) && arr_obj.push(new_obj)