如果存在多个值,则筛选数组以仅返回一个值

时间:2014-08-25 20:11:56

标签: javascript arrays

我想过滤一个数组,只返回一个城市名称,如果存在多个城市名称。

例如,底部代码的理想输出是:

纽约

俄亥俄

火星

----这是当前的输出----

纽约

俄亥俄

纽约

火星

var people = [{
    name: "jack",
    age: 22,
    city: "new york"
}, {
    name: "john",
    age: 35,
    city: "ohio"
}, {
    name: "travis",
    age: 21,
    city: "new york"
}, {
    name: "david",
    age: 42,
    city: "mars"
}];

for (var i = 0; i < people.length; i++) {
    console.log(people[i].city);   
}

jsfiddle:http://jsfiddle.net/q3nj6ey1/1/

1 个答案:

答案 0 :(得分:2)

如果城市中不存在该城市,则添加到新阵列。

var cities  = [];
var numPeople = people.length;
for (var i = 0; i < numPeople; i++) {
    if(cities.indexOf(people[i].city) == -1){
        cities.push(people[i].city);
    }
}

然后,如果您愿意,可以打印数组:

for(var i=0;i<cities.length;i++){
    console.log(cities[i]);
}