检查数组值是升序还是降序 [英] Check if array values are ascending or descending

查看:125
本文介绍了检查数组值是升序还是降序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历数组的值,并判断数组值是升序,降序还是都不行.这是我目前所拥有的,但是我无法弄清楚自己在做错什么吗?

I need to loop over the values of an array and tell if the array values are ascending, descending, or neither. This is what I have currently, but I cant figure out what I am doing wrong?

我已经看到了解决此问题的另一种方法,但是我确信我朝着正确的方向前进,并且由于我正在学习,所以我想继续遵循当前的逻辑.谢谢!

I have seen a different method to solve this, but I'm sure I am going in the right direction and since I'm learning I want to keep pursuing with my current logic. Thanks!

function ascDscArray(array) {
    for (var i=1; i < array.length-1; i++) {
        if (array[i-1] < array[i]) return "yes, ascending";
        if (array[i-1] > array[i]) return "yes, descending";
        else return "no";
    }
}

注意:这是我尝试用[15, 7, 3, -8][4, 2, 30]测试的两个示例数组.

Note: Here are two example arrays that I am trying to test with [15, 7, 3, -8], and [4, 2, 30].

推荐答案

您可以预先检查两个元素,然后选择比较功能,然后使用

You could use a check for two elements in advance and select a comparison function and check all elements with Array#every. This allows to use a short circuit if a previous element and the actual element does not match the expected order.

然后返回未排序数组的顺序或消息的类型.

Then return the type of the order or the message, that the array is not ordered.

function check(array) {
    var direction = array[0] < array[1]
            ? { type: 'asc', fn: (a, b) => a < b }
            : { type: 'desc', fn: (a, b) => a > b };

    return array.every((v, i, a) => !i || direction.fn(a[i - 1], v))
        ? direction.type
        : 'no';
}

console.log([[15, 7, 3, -8], [4, 2, 30], [1, 2, 3]].map(check));

一个版本,该版本使用给定的代码并将第一个元素与所有后续元素进行补偿.为了存储方向,使用了两个变量并在条件下更新了蜂.

A version, which uses the given code and compairs the first element with all following elements. For storing the direction two variables are used and beeing updated in conditions.

稍后检查两个变量是否均为true,然后返回'no'或方向.

Later check if both variables are true, then return 'no' or the direction.

缺点:迭代所有元素

function ascDscArray(array) {
    var asc = false, desc = false;
    for (var i = 1; i < array.length; i++) {
        if (array[0] < array[i]) {
            asc = true;
        }
        if (array[0] > array[i]) {
            desc = true;
        }      
    }
    if (asc && desc) return 'no';
    return asc ? 'asc' : 'desc';
}

console.log([[15, 7, 3, -8], [4, 2, 30], [1, 2, 3]].map(ascDscArray));

这篇关于检查数组值是升序还是降序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆