数字数组

时间:2016-09-01 09:18:24

标签: javascript arrays math

所以..我正在处理一些我需要知道的事情,如果一组有序数字有任何"提升"它,或换句话说,不是完全降序排列。

如果我有[3,2,1],它应该返回false,而对于那些数字的任何其他顺序,它应该返回true。例如。 [2,3,1],因为从左到右,海拔在2到3之间。

我使用以下小功能:

function hasElevation(digits) {
    return digits.slice().sort().reverse().toString() !== digits.toString();
}

我的问题是,有更有效的方法吗?

香草JS请!

更新:添加用例

hasElevation([3,5,4]); // true
hasElevation([3,4,4]); // true
hasElevation([1]); // false
hasElevation([1,1]); // false
hasElevation([5,4,3]); // false

2 个答案:

答案 0 :(得分:3)

您可以使用Array#some查看每个元素和前一个元素。



function hasElevation(digits) {
    return digits.some(function (a, i, aa) {
        return aa[i - 1] < a;
    });
}

console.log(hasElevation([3, 5, 4])); // true
console.log(hasElevation([3, 4, 4])); // true
console.log(hasElevation([1]));       // false
console.log(hasElevation([1, 1]));    // false
console.log(hasElevation([5, 4, 3])); // false
&#13;
&#13;
&#13;

ES6

&#13;
&#13;
var hasElevation = digits => digits.some((a, i, aa) => aa[i - 1] < a);

console.log(hasElevation([3, 5, 4])); // true
console.log(hasElevation([3, 4, 4])); // true
console.log(hasElevation([1]));       // false
console.log(hasElevation([1, 1]));    // false
console.log(hasElevation([5, 4, 3])); // false
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果[2,2]应该返回true,这将是我的解决方案

function isDescending(arr){
  return !arr.reduce((b,e,i) => b && Math.sign(arr[i]-(arr[i+1]||-Infinity)) === 1 ,true);
}

console.log(isDescending([4,3,2,1]));
console.log(isDescending([1,2,3,4]));
console.log(isDescending([4,3,2,2,1]));

如果[2,2]应该返回false

,这将是我的解决方案

function isDescending(arr){
  return !arr.reduce((b,e,i) => { var sign = Math.sign(arr[i]-(arr[i+1]||-Infinity));
                                  return b && (sign === 0 || sign === 1);
                                },true);
}

console.log(isDescending([4,3,2,1]));
console.log(isDescending([1,2,3,4]));
console.log(isDescending([4,3,2,2,1]));