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 

Output

And the output in the console will be −

[ [ 'TOP', 'LEFT' ] ]
Updated on: 2020-11-24T10:46:46+05:30

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements