假设我有以下内容:
var array =
[
{"name":"Joe", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35}
]
获得所有不同年龄的数组的最佳方法是什么,这样我就得到了一个结果数组:
[17, 35]
是否有一些方法,我可以选择结构数据或更好的方法,这样我就不必遍历每个数组检查“年龄”的值,并检查另一个数组是否存在,如果没有添加它?
如果有某种方法可以让我不用迭代就能得到不同的年龄……
目前效率低下的方式,我想改进…如果它的意思不是“数组”是一个对象的数组,而是一个对象的“映射”与一些唯一的键(即。"1,2,3")也可以。我只是在寻找最高效的方式。
以下是我目前的做法,但对我来说,迭代似乎只是为了提高效率,即使它确实有效……
var distinct = []
for (var i = 0; i < array.length; i++)
if (array[i].age not in distinct)
distinct.push(array[i].age)
这里有一个通用的解决方案,它使用reduce,允许映射,并保持插入顺序。
items:数组
mapper:将项映射到条件的一元函数,或者为空映射项本身。
function distinct(items, mapper) {
if (!mapper) mapper = (item)=>item;
return items.map(mapper).reduce((acc, item) => {
if (acc.indexOf(item) === -1) acc.push(item);
return acc;
}, []);
}
使用
const distinctLastNames = distinct(items, (item)=>item.lastName);
const distinctItems = distinct(items);
你可以把它添加到你的数组原型中,如果这是你的风格,可以省略items参数。
const distinctLastNames = items.distinct( (item)=>item.lastName) ) ;
const distinctItems = items.distinct() ;
您还可以使用Set而不是Array来加快匹配速度。
function distinct(items, mapper) {
if (!mapper) mapper = (item)=>item;
return items.map(mapper).reduce((acc, item) => {
acc.add(item);
return acc;
}, new Set());
}
高效和干净的方法,使用iter-ops库:
import {pipe, distinct, map} from 'iter-ops';
const array =
[
{name: 'Joe', age: 17},
{name: 'Bob', age: 17},
{name: 'Carl', age: 35}
];
const i = pipe(
array,
distinct(a => a.age),
map(m => m.age)
);
const uniqueAges = [...i]; //=> [17, 35]
这个函数可以唯一数组和对象
function oaunic(x,n=0){
if(n==0) n = "elem";
else n = "elem."+n;
var uval = [];
var unic = x.filter(function(elem, index, self){
if(uval.indexOf(eval(n)) < 0){
uval.push(eval(n));
return index == self.indexOf(elem);
}
})
return unic;
}
像这样使用
tags_obj = [{name:"milad"},{name:"maziar"},{name:"maziar"}]
tags_arr = ["milad","maziar","maziar"]
console.log(oaunic(tags_obj,"name")) //for object
console.log(oaunic(tags_arr)) //for array
你可以使用lodash来写一段不那么冗长的代码
方法1:嵌套方法
let array =
[
{"name":"Joe", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35}
]
let result = _.uniq(_.map(array,item=>item.age))
方法二:方法链式或级联式
let array =
[
{"name":"Joe", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35}
]
let result = _.chain(array).map(item=>item.age).uniq().value()
您可以从https://lodash.com/docs/4.17.15#uniq阅读有关lodash的uniq()方法