Split an array of objects by property value with Javascript -
i have array objects in it. need create multiple arrays objects grouped 1 of properties value. clarify here array:
var people = [ new person("scott", "guthrie", 38), new person("scott", "johns", 36), new person("scott", "hanselman", 39), new person("jesse", "liberty", 57), new person("jon", "skeet", 38) ];
i want have 1 array people first name scott, 1 first name jesse , on. suggestions helpful.
to that, can loop through array entries (in any of several ways, let's use foreach
here) , create object or map
keyed names come across, value being arrays of entries names.
here's example using object:
// create object no prototype, doesn't have "tostring" // or "valueof", although unlikely names people have var namearrays = object.create(null); // loop people array people.foreach(function(person) { // name array person's name, if var namearray = namearrays[person.firstname]; if (!namearray) { // there wasn't one, create namearray = namearrays[person.firstname] = []; } // add entry namearray.push(person); });
live example:
function person(firstname, lastname, age) { this.firstname = firstname; this.lastname = lastname; this.age = age; } var people = [ new person("scott", "guthrie", 38), new person("scott", "johns", 36), new person("scott", "hanselman", 39), new person("jesse", "liberty", 57), new person("jon", "skeet", 38) ]; // create object no prototype, doesn't have "tostring" // or "valueof", although unlikely names people have var namearrays = object.create(null); // loop people array people.foreach(function(person) { // name array person's name, if var namearray = namearrays[person.firstname]; if (!namearray) { // there wasn't one, create namearray = namearrays[person.firstname] = []; } // add entry namearray.push(person); }); // show results object.keys(namearrays).sort().foreach(function(firstname) { snippet.log( "people named " + firstname + ": " + namearrays[firstname].map(function(person) { return person.firstname + " " + person.lastname; }).join(", ") ); });
<!-- script provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
es2015 adds map
s language, in es2015 environment might use map
rather object our namearrays
:
// creating map: let namearrays = new map(); // getting array: namearray = namearrays.get(person.firstname); // adding array: namearrays.set(person.firstname, []); // looping through map: (let [firstname, namearray] of namearrays) { // use `firstname` , `namearray` here }
Comments
Post a Comment