6

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.

5
  • Are the values in array2 unique? Commented Apr 2, 2018 at 2:01
  • @ArmanCharan Yes.. Commented Apr 2, 2018 at 2:02
  • If there are multiple "2"s in array1: should they all be split points? Or just the first occurrence? Commented Apr 2, 2018 at 2:03
  • @ArmanCharan the values inside array1 also unique Commented Apr 2, 2018 at 2:04
  • Without it being in sorted order, the time complexity will grow substantially Commented Apr 2, 2018 at 2:27

2 Answers 2

9

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"]

Sign up to request clarification or add additional context in comments.

1 Comment

My preferred answer if the code (primarily arrow functions) was less concise and more readable. Still +1. Like the way it reads if (set.has(value)) .. you can't make JavaScript anymore like pseudo-code than that. Well done
0

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.

10 Comments

Why the downvote? A comment would be nice to know what could be improved.
I did not downvote this, but note that your answer is O(M*N), while the answer by @Arman Charan is only O(M).
That's what's frustrating about SO. A downvote without anything to suggest there is something wrong with the answer, the explanation, or any idea on what to improve.
im not good with arrays I just want to know how you come up with O(M*N) ? @Phrogz
Yes. The O(M*N) complexity is a result of using Array.prototype.includes() within a for loop.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.