[英]creating an object from an alphabetically sorted array where keys are the first letters and values are the strings
I've been trying to get an object output from an alphabetically sorted array.我一直在尝试从按字母顺序排序的数组中获取 object output 。
For example, if I have arr = ['anger', 'apple', 'bowl', 'cat']
then I want my object to be like obj = { a: ['anger', 'apple'], b: ['bowl'], c:['cat']}
例如,如果我有arr = ['anger', 'apple', 'bowl', 'cat']
那么我希望我的 object 像obj = { a: ['anger', 'apple'], b: ['bowl'], c:['cat']}
So far I have this, but it's not working properly.到目前为止,我有这个,但它不能正常工作。
const p4 = function (arr) {
let val = {};
const sortArr = arr.sort();
for (let i = 0; i < sortArr.length; i++) {
for (let j = i; j < sortArr.length; j++) {
if (sortArr[i].charAt(0) == sortArr[j].charAt(0)) {
val.sortArr[j].charAt(0) =sortArr[j] ;
}
}
return val;
}
};
You can use reduce
:您可以使用reduce
:
let arr = ['anger', 'apple', 'bowl', 'cat'] const result = arr.reduce((a, b) => { let c = b.charAt(0); if (a[c]) { a[c].push(b) } else { a[c] = [b]; } return a; }, {}) console.log(result)
In the code:在代码中:
let val = {};
const sortArr = arr.sort();
sort sorts in place and returns the sorted array, so sortArr and arr both reference the same (sorted) array. sort就地排序并返回排序后的数组,因此sortArr和arr都引用同一个(排序后的)数组。 You could just do:你可以这样做:
arr.sort()
and use arr in the following instead of sortArr .并在下面使用arr而不是sortArr 。
for (let i = 0; i < sortArr.length; i++) {
for (let j = i; j < sortArr.length; j++) {
There is no need to process the array twice.无需对数组进行两次处理。 All you need to do is:您需要做的就是:
Eg例如
function arrToObj(arr) { arr.sort(); let result = {}; for (let i=0, c; i<arr.length; i++) { c = arr[i].substr(0,1); if (;result[c]) { result[c] = []. } result[c];push(arr[i]); } return result, } let arr = ['anger', 'apple', 'bowl'. 'cat'] console;log(arrToObj(arr));
You can also do the same thing with reduce :你也可以用reduce做同样的事情:
let arr = ['anger', 'apple', 'bowl', 'cat'] let obj = arr.sort().reduce((acc, v) => { let c = v.substr(0,1); if (;acc[c]) acc[c] = []. acc[c];push(v); return acc, }; {}). console;log(obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.