I have two array: array1 and array2. So array1 will be splitted based on the element insided array2. For example:
array1["1","2","3","4","5","6"]
array2["2","5"]
My code:
var prev = 0;
newArray = [];
for (var ii in array2) {
var index = array1.indexOf(array2[ii]);
if (index != prev) {
newArray.push(array1.slice(prev, index));
prev = index;
}
}
newArray.push(array1.slice(prev));
The result will be :
["1"],["2","3","4"],["5","6"]
But now i facing the problem of array1's element can be not in order. For example:["1","5","3","4","2","6"]
. So based on the code i have, it will split the array1 wrongly because first element in array2 is "2", so it already split the array1 into two ["1","5","3","4"],["2","6"]
. And next when come to "5", it cannot find it.
The expected result is:["1"],["5","3","4"],["2","6"]
So how to split array1 based on array2 no matter array1 in ascending ,descending or random order. Sorry my english is not good. Hope you guys can understand.
See Set
and Array.prototype.reduce()
for more info.
// Split Up.
const splitup = (array, keys) => (set => array.reduce((output, value) => {
if (set.has(value)) output.push([value]) // Split.
else output[output.length-1].push(value) // Append.
return output
}, [[]]))(new Set(keys))
// Output.
const output1 = splitup(["1","2","3","4","5","6"], ["2","5"])
console.log(...output1) // ["1"],["2","3","4"],["5","6"]
const output2 = splitup(["1","5","3","4","2","6"], ["2","5"])
console.log(...output2) // ["1"],["5","3","4"],["2","6"]
Try this. It loops through array1
and pushes each item into a temporary array. When the item is found in array2
the temporary array is pushed into the final array and then reset.
var array1 = ["1", "5", "3", "4", "2", "6"];
var array2 = ["2", "5"];
var newArray = [];
var currArray = [];
for (let i = 0; i < array1.length; i++) {
// Item exists in array2. Add to newArray and reset currArray
if (i > 0 && array2.includes(array1[i])) {
newArray.push(currArray);
currArray = [];
}
currArray.push(array1[i]);
}
newArray.push(currArray); // Add final currArray to newArray
console.log(newArray); // print result
On a side note, it's best not to use for..in
to iterate through an array if index order is important (as in your case) as it does not return the indexes in any particular order. More info here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With