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

JavascriptWeb DevelopmentObject Oriented Programming

Suppose we have two arrays, for an 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 the arrays are bound to have the same length. We are required to write a function that when provided with an element from the second array, returns a subarray from the first array of the 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 on indices 1, 2, 4, 5, 7, at which in the second array 0’s is present.

Therefore, now let’s write the code for this function −

Example

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));

Output

The output in the console will be −

[ 'b', 'c', 'e', 'f', 'h' ]
[ 'a', 'd', 'g' ]
raja
Published on 26-Aug-2020 15:11:07
Advertisements