简体   繁体   English

我正在尝试使用javascript中的选择排序算法对数组中的对象进行排序

[英]I'm trying to sort the objects in the array using selection sort algorithm in javascript

Here's what I'm trying to output: 这是我要输出的内容:

[ { name: 'harry', age: '21' },
  { name: 'john', age: '23' },
  { name: 'jack', age: '25' } ]

but I'm getting this: 但我得到这个:

[ { name: 'john', age: '23' },
  { name: 'harry', age: '21' },
  { name: 'jack', age: '25' } ]

Here's my code: 这是我的代码:

  var persons = [
  {
  "name": "john",
  "age": "23"
  },
  {
  "name": "harry",
  "age": "21"
  },
  {
  "name": "jack",
  "age": "25"
  }
];

function selectionSortObjects (arr){
  var length = arr.length;
  for(var i = 0; i < length; i++){
    var min = [i].age;
    for(var j = i+1; j < length; j++) {
      if(arr [j].age > arr[min]){
        min = [j].age;
      }
    }
    if (min != i.age) {
      var k = arr[i].age;
      arr[i].age = arr[min];
      arr[min] = k;
    }
  }
  return arr;
}

console.log(selectionSortObjects(persons));
// console.log(persons[0].age);

What am I doing wrong? 我究竟做错了什么? Because I'm getting no errors, but I'm getting the wrong output. 因为没有错误,但是输出错误。 I'm trying to sort the result by age doing the selection sort algorithm . 我正在尝试使用选择排序算法按年龄对结果进行排序

You asked for selection sort method. 您要求选择排序方法。 This is not it but will give you the result you want based on the input provided. 并不是这样,但是会根据提供的输入为您提供所需的结果。

persons.sort(function(a, b){return a.age-b.age});

Since persons is an array we can use the array sort and pass a custom function that compares the age within each object within the array 由于人员是一个数组,我们可以使用数组排序并传递一个自定义函数,该函数比较数组中每个对象的年龄

I modified your selectionSortObjects function to make it works as you expected. 我修改了selectionSortObjects函数以使其按预期工作。 Here is the new version: 这是新版本:

function selectionSortObjects (arr){
  var length = arr.length;
  for(var i = 0; i < length; i++){
      var min = {
          value: arr[i],
          index: i
      }
    for(var j = i+1; j < length; j++) {
      if(arr[j].age < min.value.age){
        min.value = arr[j];
          min.index = j;
      }
    }
    if (min.value != arr[i]) {
      var k = arr[i];
      arr[i] = min.value;
      arr[min.index] = k;
    }
  }
  return arr;
}

Take a look at full source code in JSFiddle . 看看JSFiddle中的完整源代码。

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

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