Ad
How I Can Split My Array To Multiple Arrays Based In A Value With Javascript?
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 :
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad