在JavaScript中对二维数组进行排序的简单方法是什么?

huangapple go评论47阅读模式
英文:

Simple way to sort 2d array in Javascript?

问题

You can sort the 2D array based on the value of pairs using the following code:

let arr = [[0,23],[19,30],[6,47],[5,59],[1,56],[1,20],[19,10]];
let result = arr.sort((a, b) => a[1] - b[1] || a[0] - b[0]);
console.log(result);

This code sorts the array first by the second element of each subarray (the value), and if those are equal, it sorts by the first element (the first number). This will give you the desired sorted result.

英文:

I have a 2d array like this:

[[0,23],[19,30],[6,47],[5,59],[1,56],[1,20],[19,10]]

How can I sort that based on the value of pairs like this:

[[0,23],[1,20],[1,56],[5,59],[6,47],[19,10],[19,30]]

Here is my attempt:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let arr = [[0,23],[19,30],[6,47],[5,59],[1,56],[1,20],[19,10]];
let result = arr
              .map(a =&gt; `${a[0]}.${a[1]}`)
              .sort()
              .map(a =&gt; [parseInt(a.split(&#39;.&#39;)[0]),parseInt(a.split(&#39;.&#39;)[1])]);
console.log(result);

<!-- language: lang-css -->

.as-console-row-code {
  white-space: initial !important;
}

<!-- end snippet -->

The below code still gives wrong result. Any advice for a simple solution?

答案1

得分: 6

你可以按第一个和第二个索引值的差值进行排序。

const array = [[0, 23], [19, 30], [6, 47], [5, 59], [1, 56], [1, 20], [19, 10]];

array.sort((a, b) => a[0] - b[0] || a[1] - b[1]);

console.log(array);

如果有任何其他需要,请告诉我。

英文:

You could sort by the delta of the first and second index values.

<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const array = [[0, 23], [19, 30], [6, 47], [5, 59], [1, 56], [1, 20], [19, 10]];

array.sort((a, b) =&gt; a[0] - b[0] || a[1] - b[1]);

console.log(array);

<!-- end snippet -->

答案2

得分: 1

以下是翻译好的内容:

let arr = [[0, 23], [19, 30], [6, 47], [5, 59], [1, 56], [1, 20], [19, 10]];
let result = arr
  .sort((a, b) => {
    if (a[0] === b[0]) {
      return a[1] - b[1];
    } else {
      return a[0] - b[0];
    }
  });
console.log(result);
.as-console-row-code {
  white-space: initial !important;
}

I have commented the map statements not to convert them into strings. that makes it sorted lexicographically.
We can use custom sort function here as shown above.

英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let arr = [[0,23],[19,30],[6,47],[5,59],[1,56],[1,20],[19,10]];
let result = arr
             // .map(a =&gt; `${a[0]}.${a[1]}`)
              .sort((a,b)=&gt; {
               if (a[0] === b[0]) {
                  return a[1] - b[1];
                } else {
                  return a[0] - b[0];
                } 
              
              })
            //  .map(a =&gt; [parseInt(a.split(&#39;.&#39;)[0]),parseInt(a.split(&#39;.&#39;)[1])]);
console.log(result);

<!-- language: lang-css -->

.as-console-row-code {
  white-space: initial !important;
}

<!-- end snippet -->

I have commented the map statemens not to convert them into strings. that makes it sorted lexicographically.
We can use custom sort function here as shown above

答案3

得分: 1

类似于这个答案,但适用于任意长度的内部数字数组(不仅仅是2个元素):

function sortByNumberElements(arrA, arrB) {
  let diff = 0;
  const length = Math.min(arrA.length, arrB.length);
  for (let i = 0; i < length; i += 1) {
    diff = arrA[i] - arrB[i];
    if (diff) break;
  }
  return diff;
}

const input = [[0,23],[19,30],[6,47],[5,59],[1,56],[1,20],[19,10]];
input.sort(sortByNumberElements);

const expected = [[0,23],[1,20],[1,56],[5,59],[6,47],[19,10],[19,30]];

console.log("Equal?", JSON.stringify(input) === JSON.stringify(expected));
英文:

Similar to this answer, but works for inner number arrays of any length (not just 2 elements):

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function sortByNumberElements(arrA, arrB) {
  let diff = 0;
  const length = Math.min(arrA.length, arrB.length);
  for (let i = 0; i &lt; length; i += 1) {
    diff = arrA[i] - arrB[i];
    if (diff) break;
  }
  return diff;
}

const input = [[0,23],[19,30],[6,47],[5,59],[1,56],[1,20],[19,10]];
input.sort(sortByNumberElements);

const expected = [[0,23],[1,20],[1,56],[5,59],[6,47],[19,10],[19,30]];

console.log(&quot;Equal?&quot;, JSON.stringify(input) === JSON.stringify(expected));

<!-- end snippet -->

答案4

得分: 0

以下是您要翻译的代码部分:

const arr = [[0, 23], [19, 30], [6, 47], [5, 59], [1, 56], [1, 20], [19, 10]];

const result = arr
  .map(([a, b]) => [a, b, a + b / 100])
  .sort(([, , key1], [, , key2]) => key1 - key2)
  .map(([a, b]) => [a, b]);

console.log(result)
英文:

The original question approach with added destructuring:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    const arr = [[0, 23], [19, 30], [6, 47], [5, 59], [1, 56], [1, 20], [19, 10]];
    
    const result = arr
      .map(([a, b]) =&gt; [a, b, a + b / 100])
      .sort(([, , key1], [, , key2]) =&gt; key1 - key2)
      .map(([a, b]) =&gt; [a, b]);
    
    console.log(result)

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月17日 01:30:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定