“JavaScript Array Group” Kod odpowiedzi

Grupa JavaScript według właściwości tablica obiektów

function groupArrayOfObjects(list, key) {
  return list.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

var people = [
    {sex:"Male", name:"Jeff"},
    {sex:"Female", name:"Megan"},
    {sex:"Male", name:"Taylor"},
    {sex:"Female", name:"Madison"}
];
var groupedPeople=groupArrayOfObjects(people,"sex");
console.log(groupedPeople.Male);//will be the Males 
console.log(groupedPeople.Female);//will be the Females
Grepper

JavaScript Array Group

function groupByKey(array, key) {
   return array
     .reduce((hash, obj) => {
       if(obj[key] === undefined) return hash; 
       return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
     }, {})
}


var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];

var result = groupByKey(cars, 'make');

JSON.stringify(result,"","\t");
{
	"audi": [
		{
			"make": "audi",
			"model": "r8",
			"year": "2012"
		},
		{
			"make": "audi",
			"model": "rs5",
			"year": "2013"
		}
	],
	"ford": [
		{
			"make": "ford",
			"model": "mustang",
			"year": "2012"
		},
		{
			"make": "ford",
			"model": "fusion",
			"year": "2015"
		}
	],
	"kia": [
		{
			"make": "kia",
			"model": "optima",
			"year": "2012"
		}
	]
}
Vijaysinh Parmar

JavaScript Array Group według identyfikatora

var results = orgs.reduce(function(results, org) {
    (results[org.id] = results[org.id] || []).push(org);
    return results;
}, {})
Bewildered Bird

Grupa tablicy filtru kątowego według atrybutu

function groupBy(list, keyGetter) {
    const map = new Map();
    list.forEach((item) => {
         const key = keyGetter(item);
         const collection = map.get(key);
         if (!collection) {
             map.set(key, [item]);
         } else {
             collection.push(item);
         }
    });
    return map;
}

// example usage

const pets = [
    {type:"Dog", name:"Spot"},
    {type:"Cat", name:"Tiger"},
    {type:"Dog", name:"Rover"}, 
    {type:"Cat", name:"Leo"}
];
    
const grouped = groupBy(pets, pet => pet.type);
    
console.log(grouped.get("Dog")); // -> [{type:"Dog", name:"Spot"}, {type:"Dog", name:"Rover"}]
console.log(grouped.get("Cat")); // -> [{type:"Cat", name:"Tiger"}, {type:"Cat", name:"Leo"}]
    
    
2 Programmers 1 Bug

grupa przez JavaScript

let group = cars.reduce((r, a) => { console.log("a", a); console.log('r', r); r[a.make] = [...r[a.make] || [], a]; return r;}, {});console.log("group", group);
Bhishma'S

Odpowiedzi podobne do “JavaScript Array Group”

Pytania podobne do “JavaScript Array Group”

Więcej pokrewnych odpowiedzi na “JavaScript Array Group” w JavaScript

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu