Home > Mobile >  JS group array with before item index
JS group array with before item index

Time:10-11

I have an array like ;

arr = ["0","22","36","49","54","64","69","82","87","110","115","128","133","143","148","161","166","179","184","197","202","211","216","229","234","246","251","263","268","280","285","297","302","314","319"]

I want to create a new array like

[[0,22],[22,36],[36,49],[49,54]...[314,319], [319]]

I did like

function chunkArray(arr, len) {

    const chunkedArr = []
    arr.forEach(val => {
        const last = chunkedArr[chunkedArr.length - 1];

        if (!last || last.length === len) {
            chunkedArr.push([val]);
        } else {
            last.push(val);
        }
    });

    return chunkedArr;
}
const chunked = chunkArray(arr, 2)

But it gives me two part array like;

[["0","22"],["36","49"],["54","64"],["69","82"],["87","110"],["115","128"],["133","143"],["148","161"],["166","179"],["184","197"],["202","211"],["216","229"],["234","246"],["251","263"],["268","280"],["285","297"],["302","314"],["319"]]

CodePudding user response:

I think that what you need is something like this:

function chunkArray(arr, len) {
    const chunkedArr = [];
    for (val of arr) {
        if (chunkedArr.length) {
            const last = chunkedArr[chunkedArr.length - 1];
            if (last.length < len) {
                last.push(val);
            }
        }
        chunkedArr.push([val]);
    }
    return chunkedArr;
}

arr = ["0","22","36","49","54","64","69","82","87","110","115","128","133","143","148","161","166","179","184","197","202","211","216","229","234","246","251","263","268","280","285","297","302","314","319"];
const chunked = chunkArray(arr, 2);
console.log(chunked);

CodePudding user response:

This should do it:

const chunked = arr.map((a,i) => [a].concat(i < arr.length - 1 ? [arr[i 1]] : []));

DEMO 1

Or to generalize use:

function chunkArray(arr, len) {
    return arr.map((el,i,ar) => ar.slice(i,i len));
}

const chunked = chunkArray(arr, 3);

console.log( chunked );

DEMO 2

CodePudding user response:

Just read the next value and make a new array. When you get to the end, just append that single index

const arr = ["0", "22", "36", "49", "54", "64", "69", "82", "87", "110", "115", "128", "133", "143", "148", "161", "166", "179", "184", "197", "202", "211", "216", "229", "234", "246", "251", "263", "268", "280", "285", "297", "302", "314", "319"]

const result = arr.map((x, i, a) => i < a.length - 1 ? [ a[i   1],  x] : [ x]).filter(Boolean);

console.log(result);

CodePudding user response:

let arr = ["0","22","36","49","54","64","69","82","87","110","115","128","133","143","148","161","166","179","184","197","202","211","216","229"]

let arr1=[];
arr.forEach((val,i) => {
  if(i!==0) {
   arr1.push([ arr[i-1],  val])
  } 
  if(i===arr.length-1){
   arr1.push([ val])
  }
})

console.log(arr1)
  • Related