Fernando Gomez
Fernando Gomez

Reputation: 61

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.

Upvotes: 2

Views: 203

Answers (2)

Triet Doan
Triet Doan

Reputation: 12085

I modified your selectionSortObjects function to make it works as you expected. 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.

Upvotes: 0

Web and Flow
Web and Flow

Reputation: 143

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

Upvotes: 4

Related Questions