Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

Split the array into subarray

1. Questions: Split the array into subaary uisng javscript:

Array given :

let list = [1,2,3,4,5,6,7,8,9,10];

Solutions:

1. 
let splitValue = 5, splitedArray = [];
for (let i = 0 ; i < arrLen; i++) {
    let index = Math.floor(i /splitValue);

    if (!splitedArray[index]) {
        splitedArray[index] = []
    }
    splitedArray[index].push(list[i])
}
                            
 Console.log(splitedArray) // output: [ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 10 ] ]
                            
Split with 3: output : [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]
                            
                            
2. Example 2: 
 
const perChunk = 2 // items per chunk    

const inputArray = ['a','b','c','d','e']

const result = inputArray.reduce((resultArray, item, index) => { 
    // console.log("arr", resultArray, item, index)
  const chunkIndex = Math.floor(index/perChunk)

  if(!resultArray[chunkIndex]) {
    resultArray[chunkIndex] = [] // start a new chunk
  }

  resultArray[chunkIndex].push(item)

  return resultArray
}, [])

OUtput: [['a','b'],['c','d'],['e']]

Post a Comment

0 Comments