检查行数组中的3个值是否相同

时间:2017-04-09 15:55:54

标签: javascript arrays

我想检查我的数组是否有3个连续的值。

例如

select supplier_name, min(invoce_price)
from my_table 
group by supplier_name

JSFIDDLE

我们如何检查?

8 个答案:

答案 0 :(得分:5)

最有效的方法可能是仅对输入数组进行一次迭代并计算连续相等元素的条纹。找到足够长的序列后,立即返回true。到达目的地时,返回false。



function hasConsecutive(arr, amount) {
    var last = null;
    var count = 0;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] != last) {
            last = arr[i];
            count = 0;
        }
        count += 1;
        if (amount <= count) {
            return true;
        }
    }
    return false;
}

console.log(hasConsecutive(["g", "z", "z", "z"], 3))
console.log(hasConsecutive(["g", "z", "z", "z"], 4))
&#13;
&#13;
&#13;

答案 1 :(得分:3)

在此函数中传递数组

check3inRow(dataArray)
{
        for(i=0 ; i < (dataArray.length-2) ; i++ )
        {
            if(dataArray[i] == dataArray[i+1] && dataArray[i+1] == dataArray[i+2])
            {
                return true;
            }
        }
    return false;
}

不会像forEach一样检查数组中的每个元素,如果数组有超过2个值,也会验证数组,否则它将直接返回false,将忽略最后两个元素,因为不需要比较最后两个元素。< / p>

减少检查次数,减少循环次数,可以让您获得更快的结果。

答案 2 :(得分:3)

您可以使用Array#some并检查前辈。

function check3(array) {
    return array.some(function (a, i, aa) {
        return i > 1 && a === aa[i - 2] && a === aa[i - 1];
    });
}

console.log(check3(["g", "z", "z", "z"]));                // true
console.log(check3(["g", "z", "z", "v" ,"b", "b", "b"])); // true
console.log(check3(["z", "g", "z", "z"]));                // false
console.log(check3(["z"]));                               // false
console.log(check3(["z", "z"]));                          // false

采用动态方法处理任何需要的长度

function check(array, length) {
    var count = 0,
        value = array[0];

    return array.some(function (a) {
        if (value !== a) {
            count = 0;
            value = a;
        }
        return ++count === length;
    });
}

console.log('length: 3');
console.log(check(["g", "z", "z", "z"], 3));                // true
console.log(check(["g", "z", "z", "v" ,"b", "b", "b"], 3)); // true
console.log(check(["z", "g", "z", "z"], 3));                // false
console.log(check(["z"], 3));                               // false
console.log(check(["z", "z"], 3));                          // false

console.log('length: 4');
console.log(check(["g", "z", "z", "z", "z"], 4));           // true
console.log(check(["g", "z", "z", "b" ,"b", "b", "b"], 4)); // true
console.log(check(["z", "z", "z", "a"], 4));                // false
console.log(check(["z"], 4));                               // false
console.log(check(["z", "z"], 4));                          // false
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:2)

每个项目只增加2次,速度更快

mapPoints(Borough: "Manhattan", Neighborhood: "Battery Park City", Latitude: 40.7117, Longitude: -74.0158),

为假结果牺牲一个迭代步骤可以减少每个项目只添加一次的执行时间

        for location in locations{


            let userLocation = mapView.userLocation
            let userLat = userLocation?.coordinate.latitude
            let userLong = userLocation?.coordinate.longitude

            let coordinateOne = CLLocation(latitude: userLat!, longitude: userLong!)
            let coordinateTwo = CLLocation(latitude: location.latitude, longitude: location.longitude)

            let distanceFromPoints = coordinateOne.distance(from: coordinateTwo)
            let convertToMiles = distanceFromPoints*0.00062137
            if convertToMiles >= 2 {
                print("It's greater than set amount")
            } else{
                let annotation = MGLPointAnnotation()
                filteredLocations = locations
                print("amount to come out", filteredLocations.count)
                annotation.title = location.Neighborhood
                annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
                mapView.addAnnotation(annotation)
                mapView.setCenter((mapView.userLocation?.coordinate)!, zoomLevel: 11, animated: true)

                }
            }
    animateOut()
}

更新:经过一些测试看起来第一种方法是最快的,每1000个随机阵列153μs±1μs,0-100项,其中10%具有随机定位的三脚架。对于相同的数据,第二种方法得到193μs±0μs。

我已经测试了其他一些答案并获得了以下结果

function testFor3InARow(arr){
    var i = 0,len = arr.length-2;
    while(i < len){
       if(arr[i++] === arr[i] && arr[i] === arr[i+1]){
          return true;
       }
    }
    return false;
}

答案 4 :(得分:2)

接受的答案非常幼稚,但像@fafl 's answer我的贡献是一般的,会返回n个相同的连续项目。在这里,我测试了一个1,000,000项目数组,其中填充了0..9之间的随机整数,并测试了6个连续项目,解析时间不到200ms。

&#13;
&#13;
function itemsInRow(a,n){
  return a.reduce(function(r,e,i){
                    r[0][i%n] = e;
                    r[0].every(x => x === r[0][0]) && r[1].push(r[0].slice());
                    return r;
                  }, [Array(n).fill(),[]])[1];
  
}

var arr = Array(1000000).fill().map(_ => ~~(Math.random()*10));
    res = [];
console.time("itemsInRow");
res = itemsInRow(arr,6);
console.timeEnd("itemsInRow");
console.log(JSON.stringify(res));
&#13;
&#13;
&#13;

答案 5 :(得分:1)

只需尝试

function checkIfThreeConsecutive(arr) {
  var bool = false;

  arr.forEach(function(item, index, array) {
    if (index > 1 && (arr[index] == arr[index - 1]) && (arr[index] == arr[index - 2])) {
      bool = true;
    }
  });
  return bool;
}

console.log(checkIfThreeConsecutive(["g", "z", "z", "z"]));

答案 6 :(得分:1)

使用简单的for循环

&#13;
&#13;
var arr = ["g", "z", "z", "v", "b", "b"];
var i, l = arr.length,
  status = false;
for (i = 0; i < l; i++) {
  if (arr[i] == arr[i + 1]) {
    if (arr[i + 1] == arr[i + 2])
      status = true;
  }
}
console.log(status)
&#13;
&#13;
&#13;

答案 7 :(得分:1)

简单的边界检查

function checkIf3InRow(arr) {
    var arrLength = arr.length;
    if(arrLength < 3) {
        return false;
    }

    for(var i = 1; i < arrLength; i++) {
        if(i + 1 < arrLength && arr[i-1] == arr[i] && arr[i] == arr[i+ 1]) {
            return true;
        } 
    }
    return false;
}