简体   繁体   中英

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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