2

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.

1
  • Use Array.prototype.sort and pass in a comparator function which does e.g. return b.age - a.age; Commented Oct 1, 2015 at 1:17

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

but isn't that using the sort method? I'm trying to do the selection merge algorithm.
Did not get that from the question. You mention needing to sort an array of objects. I did infer from the examples that you wanted to sort by age but was I incorrect? If so, please explain your problem in more detail in the original question
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.