-2

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

  • 6
    What you've done so far, can you please post the code – Code Maniac May 17 '22 at 14:39
  • I map this array and use ```Object.assign({}, [item.length]: item);``` but it not works :D – Lê Nhật Minh May 17 '22 at 14:42
  • 1
    Please always post the code and effort you've done so far, so that people can point out where it went wrong and it will help you learn. you need to loop over array and build an object whose keys are based on string length and value will strings of that length. – Code Maniac May 17 '22 at 14:44
  • 1
    Duplicate of [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) – Ivar May 17 '22 at 15:30

5 Answers5

1

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)
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
Torsten Barthel
  • 3,059
  • 1
  • 26
  • 22
1

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"]
}
bturner1273
  • 660
  • 7
  • 18
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)
R4ncid
  • 6,944
  • 1
  • 4
  • 18
1

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);
SSM
  • 2,855
  • 1
  • 3
  • 10
1

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)
Christian Carrillo
  • 2,751
  • 2
  • 9
  • 15