function groupSortWords(params) { let grouping = {}, afterGrouping = []; params.forEach(item => { // 单词首字母转大写 let capital = item.word.replace(/\b[a-zA-Z]+\b/g, items => { return items.charAt(0).toUpperCase(); }); // grouping[capital] 使用了对象不能有同一属性的原理 // 相当于去重 if (grouping[capital]) { grouping[capital].arr.push(item); } else { grouping[capital] = { groupingName: `${capital}`, arr: [item] } } }); // 把对象变为数组 for (const key in grouping) { if (Object.hasOwnProperty.call(grouping, key)) { const itemKye = grouping[key]; afterGrouping.push(itemKye); } } // 外层数组排序 afterGrouping = afterGrouping.sort((a, b) => { let x = a.groupingName, y = b.groupingName; return x > y ? 1 : x < y ? -1 : 0; }); // 内层数组排序 afterGrouping = afterGrouping.map(item => { item.arr = item.arr.sort((a, b) => { let x = a.word, y = b.word; return x > y ? 1 : x < y ? -1 : 0; }); return item; }) // 最终返回 return afterGrouping; } // 数据源 let words = [ { id: 1652156, word: "absolute", }, { id: 2365256, word: "every", }, { id: 3156258, word: "display", }, { id: 4695845, word: "border", }, { id: 5125369, word: "class", }, { id: 6985485, word: "background", }, { id: 7156895, word: "delete", }, { id: 8789651, word: "color", }, { id: 9369529, word: "application", }, { id: 1031562, word: "length", }, ]; // 调用函数 console.log(groupSortWords(words));
JavaScript实现分组排序单词、单词分组排序、不能实现中文首拼音排序
关注
打赏