Ad

How I Can Split My Array To Multiple Arrays Based In A Value With Javascript?

- 1 answer

I have an array and I want to split it to multiple arrays based on the value 'Finished', when I find it, I split the array.

My code is :

var input = ['urlGettingF', '├─BROKEN─aquaHTTP_404', '├─BROKEN─url1HTTP_404' , 'ok', 'urlok', 'Finished', 
            'urlGettingF2', '├─BROKEN─url1HTTP_404','├─BROKEN─url21HTTP_404', 'Finished',
            'urlGettingF3', '├─BROKEN─url3HTTP_404','├─BROKEN─url213HTTP_404', 'Finished'
];

function chunkArray(array, size) {
  let result = []
  for (value of array) {
    let lastArray = result[result.length - 1]
    if (!lastArray || lastArray.length == size) {
      result.push([value])
    } else {
      lastArray.push(value)
    }
  }
  return result
}

const x = input.findIndex(element => element.indexOf('Finished') > -1)
console.log(chunkArray(input, x + 1));

when I run it I get :

enter image description here

But I want the result will be :

[["urlGettingF", "├─BROKEN─aquaHTTP_404", "├─BROKEN─url1HTTP_404", "ok", "urlok", "Finished"], ["urlGettingF2", "├─BROKEN─url1HTTP_404", "├─BROKEN─url21HTTP_404", "Finished"], ["urlGettingF3", "├─BROKEN─url3HTTP_404", "├─BROKEN─url213HTTP_404", "Finished"]]

When I find Finished, I split my array based on her index, you can see my code in jsbin https://jsbin.com/benozuyutu/1/edit?js,console

How I can fix it ?

Ad

Answer

var input = ['urlGettingF', '├─BROKEN─aquaHTTP_404', '├─BROKEN─url1HTTP_404', 'ok', 'urlok', 'Finished',
  'urlGettingF2', '├─BROKEN─url1HTTP_404', '├─BROKEN─url21HTTP_404', 'Finished',
  'urlGettingF3', '├─BROKEN─url3HTTP_404', '├─BROKEN─url213HTTP_404', 'Finished'
];

function chunkArray(arr) {
  let result = [
    []
  ];
  let index = 0;
  arr.forEach((x, i) => {
    result[index].push(x);
    if ((i + 1) < arr.length && x.includes('Finished')) {
      index++;
      result[index] = [];
    }
  });
  return result
}
console.log(chunkArray(input));

Ad
source: stackoverflow.com
Ad