-6

Like if there are 20 elements in an array what is the quickest way to filter them out by tens?

Like for example elements, 0-9 and then 10-21?

  • 1
    I'm sorry but I'm having a hard time understanding what you mean by "filtering out by tens". Could you be a bit more specific? – VOL Sep 20 '22 at 20:39
  • 2
    What do you mean "filter them out"? Also, this is going to depend on what the arrays contain (numbers, strings, objects, etc.). Do you really need the "quickest" way, or do you need a way? – Heretic Monkey Sep 20 '22 at 20:39
  • you can at least give us a sample array with 20 elements and what your expected result looks like. We won't solve the issue for you but at least we can give you a hint or two on how to get started – Chris G Sep 20 '22 at 20:40
  • I mean `Array.from({length:20}).map((_, i) => i).filter(i => i < 10)` gets you 0-9 pretty quick. I'm not sure how you'd get the 21st element from an array of 20 elements, so 10-21 will be quite difficult. – Heretic Monkey Sep 20 '22 at 20:43
  • sorry guys I should have been more specific – user39483893 Sep 20 '22 at 20:49

2 Answers2

1

I think, what you mean is splitting the array to chunks each chunk with size equal to ten.

function chunkArray(array, size) {
  let result = []
  for (let i = 0; i < array.length; i += size) {
    let chunk = array.slice(i, i + size)
    result.push(chunk)
  }
  return result
}
let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't'];
let arrPairs = chunkArray(arr, 10);
console.log(arrPairs);
Mina
  • 14,386
  • 3
  • 13
  • 26
0

You can try:

array.reduce((accum, current) => {
  if (accum[accum.length - 1].length === 10) {
    accum.push([]);
  }

  accum[accum.length - 1].push(current);

  return accum;
},[[]])
lante
  • 7,192
  • 4
  • 37
  • 57