w3resource

JavaScript: Split values into two groups with condition

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

Split Values into Two Groups by Filter

Write a JavaScript program to split values 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 'bifurcate' that takes an array 'arr' and a filter array 'filter' as input.
const bifurcate = (arr, filter) =>
  // Reduce the array 'arr' using the filter array 'filter'.
  arr.reduce((acc, val, i) =>
    // Use the filter value at index 'i' to determine the destination array for the current value.
    (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);

// Test the 'bifurcate' function with an array and a filter array, and log the result.
console.log(bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true])); // Output: [['beep', 'boop', 'bar'], ['foo']]

Output:

[["beep","boop","bar"],["foo"]]

Flowchart:

flowchart:Split values into two groups with condition

Live Demo:

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


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that splits an array into two groups based on a corresponding boolean filter array.
  • Write a JavaScript function that divides elements into two arrays: one where a predicate is true and one where it is false.
  • Write a JavaScript program that partitions an array into two groups using a provided callback to test each element.

Go to:


PREV : Remove Falsey Values from Array.
NEXT : Curry a Function.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.