Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the smallest array from an array of arrays

I have an array of arrays, I want to get the smallest (shortest) path from paths array

paths = [ 
   ["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"],
   ["RIGHT", "LEFT", "TOP"],
   ["TOP", "LEFT"]
];

paths.map((path)=> Math.min(path.length));
like image 698
Murhaf Sousli Avatar asked Dec 16 '16 10:12

Murhaf Sousli


2 Answers

Use Array#reduce method.

var paths = [
  ["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"],
  ["RIGHT", "LEFT", "TOP"],
  ["TOP", "LEFT"]
];

console.log(paths.reduce((prev, next) => prev.length > next.length ? next : prev))
like image 127
Pranav C Balan Avatar answered Sep 19 '22 17:09

Pranav C Balan


You can use the Array sort method and compare the length of each array. This seems the most straightforward way to me.

let paths = [
  ["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"],
  ["RIGHT", "LEFT", "TOP"],
  ["TOP", "LEFT"]
];
const [shortestPath] = paths .sort((a,b) => a.length - b.length);
console.log(shortestPath);
like image 43
Saladu Saladim Avatar answered Sep 20 '22 17:09

Saladu Saladim