'Group by Length javascript [closed]
I have a array a = ["one", "two", "three", "four", "five"] and I want to count length of each string in this array and return an object:
{
3: ["one", "two"],
4: ["four", "five"],
5: ["three"]
}
How can I solve that? Thanks in advance
Solution 1:[1]
you can do it with reduce
const strings = ["one", "two", "three", "four", "five"]
const result = strings.reduce((res, s) => {
const strLength = s.length
const existing = res[strLength] || []
return {
...res,
[strLength]: [...existing, s]
}
}, {})
console.log(result)
Solution 2:[2]
var a = ["one", "two", "three", "four", "five"]
const result = {}
for (let i = 0; i < a.length; i++) {
const item = a[i]
const length = item.length
if (!result[length]) {
result[length] = []
}
result[length].push(item)
}
console.log(result)
Solution 3:[3]
You can use Array.prototype.reduce to group the strings by their length.
const
strs = ["one", "two", "three", "four", "five"],
result = strs.reduce((r, s) => {
if (!r[s.length]) {
r[s.length] = [];
}
r[s.length].push(s);
return r;
}, {});
console.log(result);
You can also do it more concisely, as shown below:
const
strs = ["one", "two", "three", "four", "five"],
result = strs.reduce((r, s) => ((r[s.length] ??= []).push(s), r), {});
console.log(result);
Solution 4:[4]
const a = ["one", "two", "three", "four", "five"]
const result = a.reduce((acc, item) => (
Object.keys(acc).find(key => key == item.length)
?? (acc[item.length] = []),
acc[item.length].push(item),
acc
), {})
console.log(result)
Solution 5:[5]
const a = ["one", "two", "three", "four", "five"]
const b = {}
a.forEach(str => {
if (b[str.length]) {
b[str.length].push(str);
}
else {
b[str.length] = [str];
}
})
console.log(b)
output:
{
3: ["one", "two"],
4: ["four", "five"],
5: ["three"]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R4ncid |
| Solution 2 | Alexander Nied |
| Solution 3 | |
| Solution 4 | |
| Solution 5 |
