Getting elements of an array depending on corresponding values of another JavaScript

Suppose we have two arrays, for example consider the following two:

const array1 = ['a','b','c','d','e','f','g','h'];
const array2 = [ 1, 0, 0, 1 , 0, 0, 1, 0];

Both arrays are bound to have the same length. We need to write a function that, when provided with an element from the second array, returns a subarray from the first array containing all elements whose index corresponds to the index of the element we took as an argument in the second array.

For example: findSubArray(0) should return:

['b', 'c', 'e', 'f', 'h']

Because these are the elements present in the first array at indices 1, 2, 4, 5, 7, where 0's are present in the second array.

Solution Using reduce() Method

Here's the implementation of the function:

const array1 = ['a','b','c','d','e','f','g','h'];
const array2 = [ 1, 0, 0, 1 , 0, 0, 1, 0];

const findSubArray = (first, second, el) => {
    if(first.length !== second.length){
        return false;
    };
    return second.reduce((acc, val, ind) => {
        if(val === el){
            acc.push(first[ind]);
        };
        return acc;
    }, []);
};

console.log(findSubArray(array1, array2, 0));
console.log(findSubArray(array1, array2, 1));
[ 'b', 'c', 'e', 'f', 'h' ]
[ 'a', 'd', 'g' ]

Alternative Solution Using filter() Method

We can also achieve the same result using the filter() method with map():

const array1 = ['a','b','c','d','e','f','g','h'];
const array2 = [ 1, 0, 0, 1 , 0, 0, 1, 0];

const findSubArrayFilter = (first, second, el) => {
    if(first.length !== second.length){
        return false;
    }
    return first.filter((item, index) => second[index] === el);
};

console.log(findSubArrayFilter(array1, array2, 0));
console.log(findSubArrayFilter(array1, array2, 1));
[ 'b', 'c', 'e', 'f', 'h' ]
[ 'a', 'd', 'g' ]

How It Works

The function works by:

  • First checking if both arrays have the same length
  • Using reduce() to iterate through the second array with index tracking
  • When the current value matches the target element, adding the corresponding element from the first array to the accumulator
  • Returning the accumulated array of matching elements

Conclusion

This approach efficiently filters elements from one array based on corresponding values in another array. The reduce() method provides a clean solution, while filter() offers a more intuitive alternative.

Updated on: 2026-03-15T23:18:59+05:30

639 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements