Search code examples
javascriptreactjsfrontendslidercarousel

JS generate subset of array with given number and slide count


I'm working on creating customized slider in reactJS for which I'm creating a function to generated expected output and this functions takes sliderItems(holds array list), slider count(variable name 'spliceCount') and with how many items it should slide(variable name 'slideBy').

let say I have a function which takes the three attributes like array, splice-count and slideBy and return me the subsets of array based on splice-count and slideby. As of now with below function I'm able to generate the output as shown in below snippet.

const list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'];
const spliceCount = 3;
const slideBy = 2;
function getSusetofArray(array, splice, slide) {
  const arrayList = [...array];
  const subsetList = [];
   while(arrayList.length > 0) {
    subsetList.push(arrayList.splice(0, splice));
  }
  return subsetList;
}
console.log(getSusetofArray(list, spliceCount, slideBy));
// current output with above function
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'], ['J', 'K']]

However, the expect out with the help of spliceCount and slideBy is needs to be like below one

expected output = [['A', 'B', 'C'], ['C', 'D', 'E'], ['E', 'F', 'G'], ['G', 'H', 'I'], ['I', 'J', 'K'], ['K']]

Solution

  • You could iterate with wanted increment of offset and slice the array by size length.

    function getSubsetOfArray(array, size, offset) {
        const
            result = [];
            
        for (let i = 0; i < array.length; i += offset) {
            result.push(array.slice(i, i + size));
        }
    
        return result;
    }
    
    console.log(getSubsetOfArray(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'], 3, 2));
    .as-console-wrapper { max-height: 100% !important; top: 0; }