Reputation: 13296
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));
Upvotes: 6
Views: 1489
Reputation: 11
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);
Upvotes: 1
Reputation: 386550
You could collect only smaller or equal length arrays.
var paths = [["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"], ["RIGHT", "LEFT", "TOP"], ["TOP", "LEFT"]],
result = paths.reduce((r, a, i) => {
if (!i || a.length < r[0].length) {
return [a];
}
if (a.length === r[0].length) {
r.push(a);
}
return r;
}, []);
console.log(result);
Upvotes: 0
Reputation: 115212
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))
Upvotes: 8