简体   繁体   English

如果存在多个值,则对数组进行过滤以仅返回一个值

[英]Filter through array to return only one value if more than one exists

I want to filter through an array to return only one city name if more than one of its kind exists. 我想通过一个数组进行过滤,如果存在多个城市名称,则仅返回一个城市名称。

For example, the ideal output for the bottom code would be: 例如,底部代码的理想输出为:

new york 纽约

ohio 俄亥俄州

mars 火星

---- this is the current output ---- ----这是当前输出----

new york 纽约

ohio 俄亥俄州

new york 纽约

mars 火星

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/ jsfiddle: http : //jsfiddle.net/q3nj6ey1/1/

Add to a new array if the city doesn't already exist in it. 如果城市不存在,请添加到新阵列中。

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);
    }
}

Then you can print your array if you wish: 然后,您可以根据需要打印数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM