0

I have this array of objects:

var vigilantes = [
    {
        "fullName": "Tony Stark",
        "classRoom": "XI",
        "city": "NYC",
        "job": "Engineer",
        "studies": "MIT",
        "markAV": 10,
    },
    {
        "fullName": "Hulk Green",
        "classRoom": "IV",
        "city": "Beijing",
        "job": "Physicist",
        "studies": "Harvard",
        "markAV": 9,
    },
    {
        "fullName": "Thor Norse",
        "classRoom": "XX",
        "city": "Oslo",
        "job": "God",
        "studies": "U of Norway",
        "markAV": 8.5,
    },
    {
        "fullName": "Bruce Wayne",
        "classRoom": "XIX",
        "city": "Gotham",
        "job": "Richamn",
        "studies": "U of Gotham",
        "markAV": 8,
    },
    {
        "fullName": "Peter Parker",
        "classRoom": "XI",
        "city": "NYC",
        "job": "Photographer",
        "studies": "Syracuse U",
        "markAV": 7.5,
    }
]

And I would like to filter it by city, BUT I need to create a new array with the objects which share the same city. In this example the desired result would be an array of two objects because they share NYC as a city:

var vigilantes = [
    {
        "fullName": "Tony Stark",
        "classRoom": "XI",
        "city": "NYC",
        "job": "Engineer",
        "studies": "MIT",
        "markAV": 10,
    },    
    {
        "fullName": "Peter Parker",
        "classRoom": "XI",
        "city": "NYC",
        "job": "Photographer",
        "studies": "Syracuse U",
        "markAV": 7.5,
    }
]

I know I could filter by city like this:

var nyc = "NYC"
var oslo = "Oslo"
var gotham = "Gotham"
var beijing = "Beijing"

var res = vigilantes.filter(function (vigilante) {
  return beijing.indexOf(vigilante.city) >= 0; 
});

But I'm looking for something easier!

Thank you very much for your help, as you can see I'm kind of new in programming!

1 Answers1

0

You could take a hash table as a reference to the arrays with the same city.

var array = [{ fullName: "Tony Stark", classRoom: "XI", city: "NYC", job: "Engineer", studies: "MIT", markAV: 10 }, { fullName: "Hulk Green", classRoom: "IV", city: "Beijing", job: "Physicist", studies: "Harvard", markAV: 9 }, { fullName: "Thor Norse", classRoom: "XX", city: "Oslo", job: "God", studies: "U of Norway", markAV: 8.5 }, { fullName: "Bruce Wayne", classRoom: "XIX", city: "Gotham", job: "Richamn", studies: "U of Gotham", markAV: 8 }, { fullName: "Peter Parker", classRoom: "XI", city: "NYC", job: "Photographer", studies: "Syracuse U", markAV: 7.5 }],
    hash = Object.create(null),
    result = [];

array.forEach(function (o) {
    if (!hash[o.city]) {
        hash[o.city] = [];
        result.push(hash[o.city]);
    }
    hash[o.city].push(o);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392