![](/img/trans.png)
[英]Filter an array of objects and return a filtered array using pure Javascript?
[英]return a filtered array of objects
我正在努力從一組對象中刪除重復對象。 我有一個數組,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; 或返回(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}]
V2:使用Set對象,您可以使用相同的方式使用數組索引:
function filterDupes(input) {
var unique = new Set();
return input.filter((obj, ix, arr) => {
if(!unique.has(obj.text)) {
unique.add(obj.text);
return true;
}
return false;
})
}
如果您不想太多更改功能:
...
return input.filter((obj, ix, arr) => {
var index = uniqueVals.indexOf(obj.text);
if(index !== -1) {
// Remove the element from unique array
uniqueVals.splice(index,1);
return true;
}
return false;
})
V1: 不正確 。 以前,您的功能有點不正確。 它實際上什么也沒做。 您僅將文本推送到數組,然后再次檢查文本是否存在於該數組中。
var storedItems = [
{text: "1", checked: false },
{text: "2", checked: false },
{text: "3", checked: false },
{text: "string", checked: false }
];
function filterDupes(input) {
//Your previous code inside function
...
return input.filter(function(obj, ix, arr) {
return uniqueVals.indexOf(obj.text) !== -1;
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.