
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 the Smallest Array from an Array of Arrays in JavaScript
Suppose, we have a nested array of arrays like this −
const arr = [ ["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"], ["RIGHT", "LEFT", "TOP"], ["TOP", "LEFT"] ];
We are required to write a JavaScript function that takes in one such array. The function then should pick the smallest subarray (smallest in sense of a number of elements contained) and return it.
Example
The code for this will be −
const arr = [ ["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"], ["RIGHT", "LEFT", "TOP"], ["TOP", "LEFT"] ]; const findShortest = (arr = []) => { const res = arr.reduce((acc, val, ind) => { if (!ind || val.length < acc[0].length) { return [val]; }; if (val.length === acc[0].length) { acc.push(val); }; return acc; }, []); return res; }; console.log(findShortest(arr));
Output
And the output in the console will be −
[ [ 'TOP', 'LEFT' ] ]
Advertisements