Rumah > Soal Jawab > teks badan
P粉0293277112023-08-22 12:54:13
Menggunakan objek Peta ES6:
/** * @description * 接受一个类型为V的数组和一个分组函数,返回按照分组函数分组的数组的Map。 * * @param list 类型为V的数组。 * @param keyGetter 一个函数,接受类型为V的数组作为输入,并返回类型为K的值。 * K通常是V的属性键。 * * @returns 按照分组函数分组的数组的Map。 */ //export function groupBy<K, V>(list: Array<V>, keyGetter: (input: V) => K): Map<K, Array<V>> { // const map = new Map<K, Array<V>>(); 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; } // 使用示例 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"}] const odd = Symbol(); const even = Symbol(); const numbers = [1,2,3,4,5,6,7]; const oddEven = groupBy(numbers, x => (x % 2 === 1 ? odd : even)); console.log(oddEven.get(odd)); // -> [1,3,5,7] console.log(oddEven.get(even)); // -> [2,4,6]
Mengenai Peta: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
P粉5904283572023-08-22 11:08:27
Jika anda ingin mengelak daripada menggunakan perpustakaan luaran, anda boleh melaksanakan versi asli groupBy()
seperti ini:
var groupBy = function(xs, key) { return xs.reduce(function(rv, x) { (rv[x[key]] = rv[x[key]] || []).push(x); return rv; }, {}); }; console.log(groupBy(['one', 'two', 'three'], 'length')); // => {"3": ["one", "two"], "5": ["three"]}