arrays - 遍历数组并仅将每个元素中的一个推送到另一个数组
问题描述
我有从服务中获得的数组,并且在该数组中我有相同的元素(例如: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);
}) }
解决方案
使用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]
推荐阅读
- java - 如何将字符转换为字符串..?
- serialization - 将未知 JSON 序列化和反序列化为二进制
- ios - Xcode 11.2.1 错误:Command CompileSwiftSources 失败,退出代码为非零
- azure - 在所有作业后任务之后运行管道任务
- php - 如何建立 Web Socket 连接?
- python - 如何将自动正则表达式字符串作为参数传递给 Python 中的函数?
- java - 如何记录嵌套的 JSON 对象 - Scala
- angular - TypeError:def.when 不是 Angular 材料表中的函数
- sql - 列“?列?” 反复指出
- html - 当我尝试在地图上添加更多标记时,“语法错误:缺失:属性 ID 之后”“未捕获的异常:对象”