查找数组的元素是否按顺序排列

时间:2016-11-30 16:17:09

标签: javascript arrays

import { Component, OnDestroy } from '@angular/core';
import { ErrorService } from './error.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
    templateUrl: 'app/error/error.component.html'
})
export class ErrorComponent implements OnDestroy {

    message: string = '';
    subscription: Subscription;

    constructor(private errorService: ErrorService) {
        this.subscription = this.errorService.update$.subscribe(
            message => {
                this.message = message;
            });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

这里,只有当数组不按顺序时,循环才会中断。

如果数组是顺序的话,我想打破循环。

这就是原因。

我有4个阵列。如果4个数组中的任何一个按序列

,我想结束循环
var arr = ["3","5","4","6"];
arr.sort();

var flag = 0;

for(var i = 1; i < arr.length; i++) {
    if(arr[i] - arr[i-1] != 1 ) {
        flag = 1;
        break;
    }
}

if(flag == 1){
    alert('not in sequence');
}else{
    alert('in sequence');
}

在这里,我尝试按顺序将标志设置为1,这样它就不会再次进入循环。

始终打印var arr1 = ["4","1","3","5"]; var arr2 = ["5","2","3","6"]; var arr3 = ["1","5","3","6"]; var arr4 = ["1","5","3","4"]; arr1.sort(); arr2.sort(); arr3.sort(); arr4.sort(); var flag = 0; for(var i = 1; i < 5; i++){ if(flag == 0){ for(var j = 1; i < eval('arr'+i).length; j++) { if(eval('arr'+i)[j] - eval('arr'+i)[j-1] != 1) { flag = 0; }else{ flag = 1; break; } } } } if(flag == 1){ alert('in sequence'); }else{ alert('not in sequence'); }

4 个答案:

答案 0 :(得分:2)

使用Array#some迭代数组。只要其中一个按顺序(inSeq()返回true),Array#some将返回true。如果所有这些都失败,Array#some将返回false。我在inSeq()函数中使用Array#every来检查元素是否递增。如果增量不是1,则循环立即返回false

&#13;
&#13;
var arr1 = ["4", "1", "3", "5"];
var arr2 = ["5", "2", "3", "6"];
var arr3 = ["1", "5", "3", "6"];
var arr4 = ["1", "5", "3", "4"];

function inSeq(arr) {
  return arr.sort(function(a, b) { return a - b; }) // the sort function is needed because you use strings instead of numbers, and it will be sorted lexicaly without the function.
    .every(function(n, i, arr) {
      return i === 0 || n - arr[i - 1] === 1;
    });
}

var result = [arr1, arr2, arr3, arr4].some(inSeq);

console.log(result);
&#13;
&#13;
&#13;

使用arrow functions的较短的ES6版本:

&#13;
&#13;
const arr1 = ["4", "1", "3", "5"];
const arr2 = ["5", "2", "3", "6"];
const arr3 = ["1", "5", "3", "6"];
const arr4 = ["1", "5", "3", "4"];

const inSeq = (input) => input.sort((a, b) => a - b)
  .every((n, i, arr) => i === 0 || n - arr[i - 1] === 1);

const result = [arr1, arr2, arr3, arr4].some(inSeq);

console.log(result);
&#13;
&#13;
&#13;

如果你想获得带序列的第一个数组,Array#some不会帮助你(除非你添加一些丑陋的代码),因为它返回一个布尔值。您可以使用简单的for循环:

&#13;
&#13;
var arr1 = ["4", "1", "3", "5"];
var arr2 = ["5", "4", "3", "6"];
var arr3 = ["1", "5", "3", "6"];
var arr4 = ["1", "5", "3", "4"];

function inSeq(arr) {
  return arr.sort(function(a, b) { return a - b; }) // the sort function is needed because you use strings instead of numbers, and it will be sorted lexicaly without the function.
    .every(function(n, i, arr) {
      return i === 0 || n - arr[i - 1] === 1;
    });
}

function findArrWithSeq(arrs) {
  for(var i = 0; i < arrs.length; i++) {
    if(inSeq(arrs[i])) {
       return i;
    }
  }
  
  return null;
}

var result = findArrWithSeq([arr1, arr2, arr3, arr4]);

console.log(result);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以按编号排序,而不是按字符串排序,并检查固有数组中的每个项目,并将结果返回到数组的外部检查。

&#13;
&#13;
var arr1 = ["4", "1", "3", "5"],
    arr2 = ["5", "2", "3", "6"],
    arr3 = ["1", "5", "3", "6"],
    arr4 = ["1", "5", "3", "4"];

function inSeq(arr) {
    arr.sort(function (a, b) { return a - b; });      
    return arr.every(function (a, i, aa) {
        return !i || +aa[i - 1] + 1 === +a;
    });
}

var result = [arr1, arr2, arr3, arr4].some(inSeq);
console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用每个

检查数组元素是否顺序的另一种方法

&#13;
&#13;
var arr1 = ["4", "1", "3", "5"];
var arr2 = ["5", "2", "3", "6"];
var arr3 = ["1", "5", "3", "6"];
var arr4 = ["1", "5", "3", "4"];
var inSeq = input => input.sort().every((x,i,arr) => i !== 0 ? x - arr[i - 1] === 1 : true);
var result = [arr1, arr2, arr3, arr4].some(x => inSeq(x));
console.log(result);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

以与原作相似的形式保留答案(虽然将逻辑移动到函数中),您可以使用以下内容:

&#13;
&#13;
var arr0 = ["4", "1", "3", "5"];
var arr1 = ["5", "2", "3", "6"];
var arr2 = ["1", "5", "3", "6"];
var arr3 = ["2", "5", "3", "4"];

var allArrays = [arr0, arr1, arr2, arr3];

function checkSequenced(arr) {
  arr.sort();
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] - arr[i - 1] != 1) {
      return false;
    }
  }

  return true;
};

function findSequencedArrayIndex(allArrs) {
  for (var i = 0; i < 4; i++) {
    if (checkSequenced(allArrs[i])) {
      return i;
    }
  }

  return -1;
}

var firstSequencedArray = findSequencedArrayIndex(allArrays);

if (firstSequencedArray >= 0) {
  console.log('First sequenced array index: ' + firstSequencedArray);
} else {
  console.log('No arrays in sequence');
}
&#13;
&#13;
&#13;