如何在排序比较函数中获取数组元素的索引?

How to get an index of an array element within a sort comparison function?

我正在看这个问题:

The sort method for arrays can take an argument that is a comparison function with two parameters—say, x and y. The function returns a negative integer if x should come before y, zero if x and y are indistinguishable, and a positive integer if x should come after y. Write calls, using arrow functions, that sort:

  1. An array of positive integers by decreasing order
  2. An array of people by increasing age
  3. An array of strings by increasing length

这是我的代码:

const posIntByDcrOrd = [5,4,3,2,1]
const peopleIncAge = [10,15,20,25,30]
const strIncLength = ['a','ab','abc','abcd']

const compFunc = (x,y) => {
    let sumNeg = y - x
    let sumPos = y + x
    if(indexOf(x) < indexOf(y)) { console.log(sumNeg) }
    else if( indexOf(x) > indexOf(y)) { console.log(sumPos) }
    else { return 0 }
}

posIntByDcrOrd.sort(compFunc(5,4))

这段代码背后的想法是:如果你可以将数组的 x 和 y 元素的索引相加,你可以得到一个负整数,因为 x 将低于 y 而 y 将高于 x,满足条件。但是当我尝试 运行 这个时,我当然得到了一个引用错误。如何访问排序数组中 x 和 y 的索引位置?我也对其他解决方案持开放态度。

P.S.: 这些数组是为了简化思考过程而编造的。

本网站上有大量关于排序的问答。您的尝试似乎表明您还没有看到数字在 JavaScript 中通常是如何排序的。例如 this Q&A 和许多其他人提供了正确的方法。

对您的尝试的一些评论:

  • sort 的回调中没有可用的 indexOf。你不需要那个信息。只需从第一个值中减去第二个值即可获得递增(非递减)结果。在另一种意义上执行减法以获得递减(非递增)结果。 sort 函数的内部将使用该 return 值来执行排序算法。在此过程中您不需要知道任何索引。

  • 关于人的分配可能没有正确反映在您的示例数组中,因为现在它看起来与第一个输入(数字数组)相同。很可能是 objects 数组。例如:

    const peopleIncAge = [{name: "Helen", age: 20},
                          {name: "John", age: 15},
                          {name: "Anne", age: 30},
                          {name: "Clark", age: 25},
                          {name: "Joy", age: 10}]
    
  • 您的输入数组已经排序,因为它们需要输出。为了测试任何解决方案,最好将它们打乱。

三个练习中的每一个都需要一个不同的 sort 函数回调函数:

const positives = [1, 3, 5, 4, 2];
const people = [{name: "Helen", age: 20},
                {name: "John", age: 15},
                {name: "Anne", age: 30},
                {name: "Clark", age: 25},
                {name: "Joy", age: 10}];
const strings = ['abc', 'a', 'abcd', 'ab'];

console.log(positives.sort((x, y) =>  y - x));  // decreasing
console.log(people.sort((x, y) =>  x.age - y.age)); // increasing age
console.log(strings.sort((x, y) =>  x.length - y.length)); // increasing length