Get the smallest array from an array of arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ] ]
raja
Published on 24-Nov-2020 10:46:31
Advertisements