
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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' ] ]
- Related Questions & Answers
- How to get single array from multiple arrays in JavaScript
- Smallest Common Multiple of an array of numbers in JavaScript
- JavaScript: create an array of JSON objects from linking two arrays
- Search from an array of objects via array of string to get array of objects in JavaScript
- Get the max n values from an array in JavaScript
- Third smallest number in an array using JavaScript
- Find the Smallest element from a string array in JavaScript
- Extract arrays separately from array of Objects in JavaScript
- Array of objects to array of arrays in JavaScript
- Converting array of arrays into an object in JavaScript
- C# Program to find the smallest element from an array
- From an array of arrays, return an array where each item is the sum of all the items in the corresponding subarray in JavaScript
- Projection of arrays to get the first array element from MongoDB documents
- Retrieving n smallest numbers from an array in their original order in JavaScript
- Get the closest number out of an array in JavaScript
Advertisements