
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Elements of an Array Based on Corresponding Values in JavaScript
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' ]
Advertisements