排序一个数组,数组中的项最接近中间值两个,另一端的其他极端值-js [英] sort an array with item closest to two in middle and other extremes on other side - js

查看:64
本文介绍了排序一个数组,数组中的项最接近中间值两个,另一端的其他极端值-js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对数组中的3个数字进行排序,以便最接近2的项位于中间,从左起的两个数字中最小,从右起的两个数字中最高.

I have 3 numbers in an array that I want to order so that the item closest to 2 is in the middle, the lowest from two on the left and the highest from two on the right.

示例1-[2.3, 5.2, 1.2];应更改为[1.2, 2.3, 5.2];

示例2-[1.1, 2.3, 0.3];,应更改为[0.3, 2.3, 1.1];

示例3-[1.3, 0.3, 2];,应更改为[0.3, 2, 1.3];

示例4-[2.2, 2.3, 2.1];,应更改为[2.2, 2.1, 2.3];

当前,我有以下内容,但订购不正确.这样会将最接近2的项目放在最前面.

Currently I have the following but this is not ordering correctly. This puts the item closest to 2 at the front.

arr.sort(function(a, b){
    return Math.abs(1 - (a - 2)) - Math.abs(1 - (b - 2));
});

任何人都可以看到需要如何更改吗?

Can anyone see how this needs to be changed?

推荐答案

您需要采用三步方法,首先进行排序以获得最接近给定值的值,然后对该值进行移位,然后对其余的升序进行排序.然后将临时值拼接到索引1.

You need a three step approach, first sort to get the closest to the given value, shift that value and sort the rest ascending. Then plice the temporary value to index 1.

function sort(array) {
    var temp = array.sort((a, b) => Math.abs(x - a) - Math.abs(x - b)).shift();
    array.sort((a, b) => a - b).splice(1, 0, temp);
    return array;
}

var x = 2;
console.log(sort([0, 1, 2]));
console.log(sort([1, 2, 3]));
console.log(sort([2, 3, 4]));

.as-console-wrapper { max-height: 100% !important; top: 0; }

另一种解决方案是在新数组中收集具有较大增量的值并将其排序.稍后将减少的值放回索引1.

Another solution would be to collect the values with bigger delta in a new array and sort it. Later put the reduced value back to index 1.

优点:不需要多余的排序,而只需要进行一次迭代即可.

Advantage: No superfluous sort, while only one iteration is needed.

function sort(array) {
    var temp = [],
        value = array.reduce((a, b) =>
            Math.abs(x - a) < Math.abs(x - b) ? (temp.push(b), a) : (temp.push(a), b)
        );

    temp.sort((a, b) => a - b).splice(1, 0, value);
    return temp;
}

var x = 2;
console.log(sort([0, 1, 2]));
console.log(sort([1, 2, 3]));
console.log(sort([2, 3, 4]));

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于排序一个数组,数组中的项最接近中间值两个,另一端的其他极端值-js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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