在Java迭代中映射和排序? [英] Map and Sort in one iteration in Javascript?

查看:66
本文介绍了在Java迭代中映射和排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能将一个数组映射到一个新数组并同时对其进行排序,而无需重复两次(对于第一个数组的映射一次,对第二个数组的排序一次)?使用这种map方法时,我一直在尝试使用匿名函数对其进行排序:

var arr=[4,2,20,44,6];
var arr2=arr.map(function(item, index, array){
    if(index==array.length-1 || item==array[index+1]){
        return item;
    }
    else if((item-array[index+1])<0){
        return item;
    }
    else if((item-array[index+1])>0){
        return array[index+1];
    }
});
console.log(arr2);

但是它似乎不起作用.我在这里是如何实现此目标的,还是我的代码有问题?

解决方案

排序通常需要一个以上的迭代.平均情况下几乎可以确定为O(n log n)(ECMAScript未指定该算法,但这是比较排序所能做到的最好),因此同时进行这两个步骤没有多大意义. /p>

但是,您可以将它们链接为一个表达式,因为sort返回数组本身:

function order(a, b) {
    return a < b ? -1 : (a > b ? 1 : 0);
}
var arr2 = arr.map(function(item) { ... }).sort(order);

Is it possible to map an array to a new array and to sort it at the same time without iterating twice (once for the map on the first array and once for the sort on the second array)? I've been trying to sort it with an anonymous function when using the map method like this:

var arr=[4,2,20,44,6];
var arr2=arr.map(function(item, index, array){
    if(index==array.length-1 || item==array[index+1]){
        return item;
    }
    else if((item-array[index+1])<0){
        return item;
    }
    else if((item-array[index+1])>0){
        return array[index+1];
    }
});
console.log(arr2);

but it doesn't seem to work. Am I way off base here in how I'm trying to implement this, or is there just a problem with my code?

解决方案

Sorting generally takes more than one iteration by itself. It's almost certainly O(n log n) for the average case (the algorithm isn't specified by ECMAScript, but that's the best you can do with a comparison sort), so there's not much point in doing both at the same time.

You can chain them into one expression though, since sort returns the array itself:

function order(a, b) {
    return a < b ? -1 : (a > b ? 1 : 0);
}
var arr2 = arr.map(function(item) { ... }).sort(order);

这篇关于在Java迭代中映射和排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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