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));
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))
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With