首页 > 解决方案 > 遍历数组并仅将每个元素中的一个推送到另一个数组

问题描述

我有从服务中获得的数组,并且在该数组中我有相同的元素(例如:1、2、2、3、1、1、3)。我想制作另一个数组,它只包含前一个数组中的每个元素中的一个(所以新数组应该看起来像 [1,2,3 等)。你能指出我在这个函数中的错误吗?谢谢

this.dataService.get().subscribe( response => {

        this.Data = response;
        response.forEach(res => {
            for (this.i = 0; this.i < this.headData.length; this.i++){
                res.head !== this.headData[this.i];
            }
            this.headData.push(res.head);
        }) }

标签: arraysangularloops

解决方案


使用Set 生成数组中的唯一项

var items = [1,2,2,3,1,1,3]
var uniqueItems = Array.from(new Set(items))

参考

或者你可以使用sortedUniq Lodash 函数

_.sortedUniq([1, 1, 2]);
// this is the result  => [1, 2]

推荐阅读