Romil Gandhi Romil Gandhi - 3 months ago 11
Javascript Question

Sort index of array based on value

I get the wrong index value when i am adding more than 10 values in my observable array, when i am trying to get current object like observableArray.indexOf(this). So i created new variable index value and generated like below example. But on enter i want to sort my observable array in descending order. So I want to do something like below example.

I have list of object with value like below

1,20
2,40
3,10
4,50


And I want result like

3,20
2,40
4,10
1,50


I want to sort my index value based on descending order of number in knockout observable.

Answer
  • Sort an mapped array based on value.
  • Find the index of value based on the index from sorted array.

var obj = [{
  index: 1,
  value: 20
}, {
  index: 2,
  value: 40
}, {
  index: 3,
  value: 10
}, {
  index: 4,
  value: 50
}];
var sortedArr = obj.map(function(el) {
  return el.value;
}).sort(function(a, b) {
  return b - a
});
var mapped = obj.map(function(el) {
  var index = sortedArr.indexOf(el.value) + 1;
  el.index = index;
  return el;
});
console.log(JSON.stringify(mapped,null,4));