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

时间:2020-04-02 22:15:54

标签: javascript node.js algorithm computer-science

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

{
 n: 15,
 color: "red"
}

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

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来显示所有这些

3 个答案:

答案 0 :(得分:0)

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

通过您可以使用Array.proototype.sort方法的方式,它看起来像:

undefined
console.log(myArr.sort((a,b) => a.n - b.n))

答案 1 :(得分:0)

尝试反对this.array [i] .n写this.array [i] [n] 并针对this.array [j] .n编写this.array [j] [n]

答案 2 :(得分:0)

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

  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" }
  // ];