I have an example array like below. what I want, how to split an array into multiple arrays if the value satisfies a condition? like an example if the next value difference exceeds 9, it will automatically create a new array. Here its sample code.
const arr = [1,2,3,4,5,6,7,8,25,26,27,28,29,50]
//exmaple result = [[1,2,3,4,5,6,7,8], [25,26,27,28,29], [50]]
I've tried using array.reduce but it doesn't work or I haven't found a way
CodePudding user response:
I believe this is what you're trying to achieve:
const arr = [1,2,3,4,5,6,7,8,25,26,27,28,29,50];
const result = arr.reduce((acc, val) => {
if (acc.length === 0 || Math.abs(acc.at(-1).at(-1) - val) > 9) {
acc.push([val]);
} else {
acc.at(-1).push(val);
}
return acc;
}, [])
console.log(result);
Where array.at(-1)
returns the last element.
CodePudding user response:
Hope this answer will help. I used array.slice() method.
read more about slice() method here
// array initialization
const arr=[1,2,3,4,5,6,7,8,25,26,27,28,29,50];
/* function which will receive an array(arr) and the difference(diff) so that
when the difference between two values at consecutive indexes(ex: arr[1] and arr[2]) exceeds the diff, we will create new array.
*/
const findSubArrays=(arr,diff)=>{
let newArray=[];
let startIndex=0;
for(let i=0;i<=arr.length;i ){
let nextIndex=i 1;
if(arr[nextIndex]-arr[i]>diff){
newArray.push([...arr.slice(startIndex,i)]);
startIndex=i;
}
}
return newArray;
}
const result=findSubArrays(arr,9);
console.log(result);//prints [ [ 1, 2, 3, 4, 5, 6, 7 ], [ 8, 25, 26, 27, 28 ],[50] ]