w3resource

JavaScript: Split values of two given arrays into two groups

JavaScript fundamental (ES6 Syntax): Exercise-17 with Solution

Write a JavaScript program to split the values of two given arrays into two groups. If an element in the filter is true, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.

  • Use Array.prototype.reduce() and Array.prototype.push() to add elements to groups, based on filter.
  • If filter has a truthy value for any element, add it to the first group, otherwise add it to the second group.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
// Define a function called `bifurcate` that splits an array into two groups based on a filter array.
const bifurcate = (arr, filter) =>
  arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]); // Split the array based on the filter array

// Example usage
console.log(bifurcate([1, 2, 3, 4], [true, true, false, true])); // [[1, 2, 4], [3]]
console.log(bifurcate([1, 2, 3, 4], [true, true, true, true])); // [[1, 2, 3, 4], []]
console.log(bifurcate([1, 2, 3, 4], [false, false, false, false])); // [[], [1, 2, 3, 4]]

Output:

[[1,2,4],[3]]
[[1,2,3,4],[]]
[[],[1,2,3,4]]

Flowchart:

flowchart: Split values of two given arrays into two groups

Live Demo:

See the Pen javascript-basic-exercise-1-17 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function that returns true if the provided predicate function returns true for all elements in a collection, false otherwise.
Next: Write a JavaScript program to remove specified elements from the left of a given array of elements.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-17.php