gpt4 book ai didi

JavaScript : Rearrange array elements according to the absolute difference with x

转载 作者:行者123 更新时间:2023-11-29 10:01:18 26 4
gpt4 key购买 nike

根据与x i 的绝对差值重新排列数组元素。即,具有最小差异的元素首先出现,依此类推。就像我正在服用array [10, 5, 3, 9, 2, 3]x = 7 那么每个元素的绝对差应该是 =

7 - 10 = 3(abs)
7 - 5 = 2
7 - 3 = 4
7 - 9 = 2(abs)
7 - 2 = 5
7 - 3 = 4

所以根据与X的不同,元素排列为[5,9,10,3,3,2]

我已经用下面的代码试过了,但还是失败了:

function ar(a, x) {
var obj = {}, d, i, res;

for (i = 0; i < a.length; i++) {
d = Math.abs(a[i] - x);
obj[a[i]] = d;
}

res = Object.keys(obj).sort(function(a, b) {
return obj[a] - obj[b]
});

for (i = 0; i < res.length; i++) {
res[i] = parseInt(res[i]);
}

return res;
}

var o = ar([10, 5, 3, 9, 2, 3], 7);
console.log(o);

如您所见,我正在制作只有一个键但值在此处重复的对象。我找不到另一种解决方法,我得到的答案是 [5,9,10,3, 2]:(..

最佳答案

as you can see I'm making object which have only one key but values repeat here

对象不能有重复的属性,所以当你重复一个属性时,它会用新值覆盖前一个属性

您可以简单地将排序与 Math.abs 一起使用

let arr = [10, 5, 3, 9, 2, 3]
let x = 7

let sortByDiff = (arr,x) => arr.sort((a,b)=> Math.abs(a-x) - Math.abs(b-x))

console.log(sortByDiff(arr,x))

关于JavaScript : Rearrange array elements according to the absolute difference with x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56696354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com