代码之家  ›  专栏  ›  技术社区  ›  Code Guy

以最少的运行时间高效地查找和返回多个值的数组位置

  •  0
  • Code Guy  · 技术社区  · 6 年前

    function getAllIndexes(arr, val) {
        var indexes = [], i = -1;
        while ((i = arr.indexOf(val, i+1)) != -1){
            indexes.push(i);
        }
        return indexes;
    }
    
    var Cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"];
    
    var indexes = getAllIndexes(Cars, "Nano");
    
    //will return 0 3 5
    

    var indexes = getAllIndexes(Cars, ["Nano","BMW"]);
    
    //should return 0 2 3 5 6
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Nina Scholz    6 年前

    您需要一种不同的方法,因为您需要寻找更多的值。

    您可以映射匹配项的索引或 -1 为以后的筛选运行查找未找到的项。

    const
        getAllIndices = (array, needles) => array
            .map((v, i) => needles.includes(v) ? i : -1)
            .filter(i => i + 1);
    
    var cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"],
        indices = getAllIndices(cars, ["Nano", "BMW"]);
    
    console.log(indices);

    function getAllIndices(array, needles) {
        return array
            .map(function (v, i) { return needles.indexOf(v) + 1 ? i : -1; })
            .filter(function (i) { return i + 1; });
    }
    
    var cars = ["Nano", "Volvo", "BMW", "Nano", "VW", "Nano"],
        indices = getAllIndices(cars, ["Nano", "BMW"]);
    
    console.log(indices);