[英]Removing duplicates with in an object array using angular 4
我有一个包含以下项目列表的数组,如图所示,我想删除重复项
[L7-LO, %L7-LO]
来自该阵列。
场景一:
this.formulalist.filter((el, i, a) => i == a.indexOf(el))
场景2:
Observable.merge(this.formulalist).distinct((x) => x.Value)
.subscribe(y => {
this.formulalist.push(y)
});
场景3:
this.formulalist.forEach((item, index) => {
if (index !== this.formulalist.findIndex(i => i.Value == item.Value))
{
this.formulalist.splice(index, 1);
}
});
上述三种情况都无法从该数组中删除重复项。 有人可以帮忙解决这个查询吗?
angular 不是必需的,使用 vanillajs 过滤仅出现一次的元素并将第一次出现的元素添加到新列表中
let newFormulalist = formulalist.filter((v,i) => formulalist.findIndex(item => item.value == v.value) === i);
尝试填充一个没有重复的新数组。 稍后将新数组分配给公式列表。
newArr = []
this.formulalist.forEach((item, index) => {
if (this.newArr.findIndex(i => i.Value == item.Value) === -1)
{
this.newArr.push(item)
}
});
this.formulalist = this.newArr
编辑
看看上面的答案,解决方案似乎已经过时了。 更好的方法是使用Array.filter()
不是Array.forEach()
。
但是,有一个更好的解决方案会很好,现在当我看到这个问题时,我觉得findIndex()
由于额外的遍历而不是一个好的方法。
我可能有一个Set
并将值存储在我想要过滤的Set
,如果Set
有这些条目,我会从数组中跳过这些元素。
或者更好的方法是 Akitha_MJ 使用的方法,非常简洁。 数组长度的一个循环,循环中的一个 Object(Map),键是我们要删除重复项的值,而值是完整的 Object(Array 元素) 本身。 在循环中重复元素时,元素将在 Map 中被简单地替换。 稍后只需从 Map 中取出值。
const result = Array.from(this.item.reduce((m, t) => m.set(t.name, t), new Map()).values());
希望这有效!!
// user reduce method to remove duplicates from object array , very easily
this.formulalist= this.formulalist.reduce((a, b) => {
if (!a.find(data => data.name === b.name)) {
a.push(b);
}
return a;
}, []);
// o/p = in formulalist you will find only unique values
使用 reducer 返回一个新的唯一对象数组:
const input = [{ value: 'L7-LO', name: 'L7-LO' }, { value: '%L7-LO', name: '%L7-LO' }, { value: 'L7-LO', name: 'L7-LO' }, { value: '%L7-LO', name: '%L7-LO' }, { value: 'L7-L3', name: 'L7-L3' }, { value: '%L7-L3', name: '%L7-L3' }, { value: 'LO-L3', name: 'LO-L3' }, { value: '%LO-L3', name: '%LO-L3' } ]; console.log(input.reduce((acc, val) => { if (!acc.find(el => el.value === val.value)) { acc.push(val); } return acc; }, []));
通过将值分配给某些对象属性,过滤唯一值要快得多 - 不会有重复项。 这种方法随着初始数组的每个 +1 成员变得越来越好,因为循环将导致快速算法复杂化
let arr = [ {value: 'L7-LO', name: 'L7-LO'}, {value: '%L7-LO', name: '%L7-LO'}, {value: 'L7-LO', name: 'L7-LO'}, {value: '%L7-LO', name: '%L7-LO'}, {value: 'L7-L3', name: 'L7-L3'}, {value: '%L7-L3', name: '%L7-L3'}, {value: 'LO-L3', name: 'LO-L3'}, {value: '%LO-L3', name: '%LO-L3'} ]; let obj = {}; const unique = () => { let result = []; arr.forEach((item, i) => { obj[item['value']] = i; }); for (let key in obj) { let index = obj[key]; result.push(arr[index]) } return result; } arr = unique(); // for example; console.log(arr);
如果您使用 ES6 及更高版本,使用 map 和 filter 函数的基本 JS 会很容易。
var array = [{value:"a"},{value:"b"},{value:"c"},{value:"a"},{value:"c"},{value:"d"}]; console.log(array.filter((obj, pos, arr) => { return arr.map(mapObj => mapObj["value"]).indexOf(obj["value"]) === pos; }));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.