gpt4 book ai didi

javascript - 返回经过过滤的对象数组

转载 作者:行者123 更新时间:2023-11-28 14:53:05 24 4
gpt4 key购买 nike

我正在努力从对象数组中删除重复项。我有一个数组,storedItems:

var storedItems = [
{text: "1", checked: false },
{text: "2", checked: false },
{text: "3", checked: false },
{text: "string", checked: false }
]

等等。文本值可以是字符串或数字字符串。我可以识别唯一的文本值,无论是在哈希中还是在 uniqueVals 中......

filterDupes(storedItems);

function filterDupes(input) {
var hash = {};
var uniqueVals = [];
input.forEach(obj => {
hash[obj.text] = true;
})
var uniqueVals = Object.keys(hash); // Array
return input.filter(function(obj, ix, arr) {
uniqueVals.indexOf(obj.text) !== -1; // NOPE
}) // .filter
} // filterDupes

...它是如何将哈希键或 uniqueVals 与输入数组对象进行比较,即,我到底需要什么(没有 for 循环或另一个 forEach?)来返回过滤后的数组,这让我痛斥我头靠墙,试图找到 return hash[obj.text] == obj.text; 的某个版本。或 return (hash.key === obj.text)

编辑:在这里摆弄:https://jsfiddle.net/WTFoxtrot/by3nhy4n/2/

最佳答案

使用 Array.prototype.map() 的组合和 Array.prototype.filter() :

let items = [
{text: "1", checked: false},
{text: "2", checked: false},
{text: "3", checked: false},
{text: "string", checked: false},
{text: "2", checked: false},
{text: "string", checked: false},
{text: "1", checked: false}
];
let values = items.map(it => it.text).filter((v, i, a) => a.indexOf(v) === i);

console.log(values); // ["1", "2", "3", "string"]

过滤器闭包 (v, i, a) => a.indexOf(v) === i 过滤掉除第一次出现该值之外的任何位置上出现的所有值.

使用相同的原理,如果您想过滤对象数组本身而不是返回唯一值列表,则可以将 Array.prototype.filter() 与 Array.prototype.find() 一起使用。 :

let items = [
{text: "1", checked: false},
{text: "2", checked: false},
{text: "3", checked: false},
{text: "string", checked: false},
{text: "2", checked: false},
{text: "string", checked: false},
{text: "1", checked: false}
];
let filtered = items.filter((x, i, a) => a.find(y => x.text === y.text) === x);

console.log(filtered); // [{"text": "1", "checked": false}, {"text": "2", "checked": false}, {"text": "3", "checked": false}, {"text": "string", "checked": false}]

关于javascript - 返回经过过滤的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43860545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com