2 回答

TA貢獻(xiàn)1943條經(jīng)驗(yàn) 獲得超7個贊
我不確定您是否想要根據(jù)值數(shù)組進(jìn)行匹配或排除,因此請?zhí)峁﹥烧撸?/p>
const arr = [{
value: "test1",
name: "name1"
},
{
value: "test2",
name: "name1"
},
{
value: "test3",
name: "name1"
},
{
value: "test3",
name: "name2"
},
{
value: "test4",
name: "name2"
},
]
const valuesToCompare = ["test1", "test2"]
const excluding = arr.filter(obj => !valuesToCompare.includes(obj.value))
console.log("Excluding values:")
console.log(excluding)
const matching = arr.filter(obj => valuesToCompare.includes(obj.value))
console.log("Matching values:")
console.log(matching)

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個贊
你可以像下面這樣做:
分組
arr
依據(jù)name
對于每個分組,過濾值
將每個組展平為對象
const arr = [
{ value: "test1", name: "name1" },
{ value: "test2", name: "name1" },
{ value: "test3", name: "name1" },
{ value: "test3", name: "name2" },
{ value: "test4", name: "name2" },
];
const valuesToCompare = ["test1", "test2", "test3", "test4"];
const groupByName = arr.reduce((acc, el) => {
if (acc[el.name]) {
acc[el.name].push(el.value);
} else {
acc[el.name] = [el.value];
}
return acc;
}, {});
const res = Object.entries(groupByName)
.map(([k, v]) => [k, valuesToCompare.filter((vtc) => !v.includes(vtc))])
.map(([k, v]) => v.map((v) => ({ name: k, value: v })))
.flat();
console.log(res);
.as-console-wrapper { max-height: 100% !important; }
添加回答
舉報