【问题标题】:Get the smallest array from an array of arrays从数组数组中获取最小的数组
【发布时间】:2017-05-02 03:45:13
【问题描述】:

我有一个数组数组,我想从paths数组中获取最小(最短)路径

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

paths.map((path)=> Math.min(path.length));

【问题讨论】:

  • 怎么了?
  • 你遇到了什么错误=
  • @AnnaJeanine 我没有收到错误,我只是不知道如何使用map 函数来实现
  • 相同长度的数组呢?
  • @NinaScholz 在我的情况下没关系 :)

标签: javascript arrays typescript ecmascript-6


【解决方案1】:

使用Array#reduce 方法。

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

console.log(paths.reduce((prev, next) => prev.length > next.length ? next : prev))

【讨论】:

  • @MurhafSousli :你可以做......但它可能会很长......这不是地图方法的工作;)
  • 好这个更好
【解决方案2】:

您只能收集更小或等长的数组。

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);

【讨论】:

    【解决方案3】:

    您可以使用数组排序方法并比较每个数组的长度。这对我来说似乎是最直接的方法。

    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);
    

    【讨论】:

      猜你喜欢
      • 2021-12-12
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 2015-10-13
      • 2015-12-22
      • 2012-02-14
      • 2023-01-05
      • 2021-03-14
      相关资源
      最近更新 更多