繁体   English   中英

使用 javascript 对对象数组进行插入排序

[英]Insertion sort on an array of objects with javascript

我有这个数组,其中的对象看起来像这样

{
 n: 15,
 color: "red"
}

我正在尝试使用以下 function 对其进行排序

async insertionSort() {
      let len = this.array.length;
      let value;
      let i;
      let j;
      //let current;
      // let arr = this.array;

      for (i = 0; i < len; i++) {
        value = this.array[i].n;
        //current = this.array[i];
        for (j = i - 1; j > -1 && this.array[j].n > value; j++) {
          //arr[j + 1] = arr[j];
          // HF.arraySwap(this.array, this.array[j + 1], this.array[j]);
          this.array[j + 1] = this.array[j];
        }
        // arr[j + 1] = value;
        HF.arraySwap(this.array, this.array[j + 1], this.array[i]);
        await HF.sleep();
      }
    }

** 我不能使用 array.sort(...) 因为我正在尝试对算法进行可视化,我正在使用对象来更改我在屏幕上呈现的条形的颜色 **当我点击第二个for循环我得到一个错误“无法读取未定义的属性'n'”,当我只用数字运行它时它工作正常但是当我用对象尝试它时它给出了错误。我现在知道我用完了数组,有没有办法可以克服这个问题并且仍然对对象数组进行排序? 另外,我正在使用 VueJS 来显示所有这些

在第一次迭代i=0时,您以值为 -1 j=i-1开始第二个循环。 数组不包含索引为 -1 的项目: array[-1] is undefined 只要 JavaScript 可以比较不同类型的变量,它就可以与数字一起使用,因为数字和未定义的比较不会触发错误

顺便说一句,您可以使用Array.proototype.sort方法,它看起来像:

 console.log(myArr.sort((a,b) => an - bn))
 <script> const myArr = [ { n: 1, color: "red" }, { n: 44, color: "orange" }, { n: 13, color: "yellow" }, { n: 8, color: "green" }, { n: 2, color: "blue" } ]; </script>

试试 this.array[i].n 写 this.array[i][n] 和 this.array[j].n 写 this.array[j][n]

有什么理由不使用这样的排序方法吗?:

  const arr = [
    { n: 10, color: "red" },
    { n: 20, color: "yellow" },
    { n: 15, color: "black" },
    { n: 7, color: "white" },
    { n: 23, color: "blue" }
  ];

  const ascSorted = arr.sort((a, b) => a.n - b.n); 
  const descSorted = arr.sort((a, b) => b.n - a.n);

  console.log(ascSorted);
  // [
  //   { n: 7, color: "white" },
  //   { n: 10, color: "red" },
  //   { n: 15, color: "black" },
  //   { n: 20, color: "yellow" },
  //   { n: 23, color: "blue" }
  // ];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM