Kulin Kulin - 4 days ago 7
Javascript Question

Best way for Order Array by Keys

I need to push new value in array, and that this value was automatically ordered.
I try to explain me:

I have an array like this:

arr[0.1] = Mark
arr[0.3] = Sonia
arr[0.5] = John


This array is filled automatically, and I'm receiving a lot of new data for add and for modify the name (value).

If I receive 0.1->Sonia, I change the value of 0.1, arr[0.1] = Sonia. But if I receive a new position, like 0.2, I need push this value between 0.1 and 0.3 positions, not in the final of array.

This is posible, or I only can sort the array after add any value?
I'm using es6, I thought I saw new format of array, that can used like list.

EDIT

Not is necessarly use an array. I only need can order this values automatically, because they are update constantly.

EDIT2

I think that here are two solutions, but I don't know how are the best.

Solution 1:

Using an object for any key->value, add this into an array, and sort array any time that add new object. (Like Your answers)
The problem here, is if the array content 1000 elements, and any second was added 10 new elements, I need to sort big array 10 times/s.
And if a value name are modified also I need loop the array of objects for found the value.

Solution 2

Using array, like my example. When I receive a object, execute a loop for any element of array, and if the key value of array is < that the new value continue, until the second value are higher.
Pseudo code:

var ObjReceived = {value:"0.125", name:"MARK"} var arr = [];

for arr.length
if(arr-key < ObjReceived.value){
continue }else{
arr[ObjReceived.value] = ObjReceived.name
}


With this code, I only need loop array, until the position is correct. And if the name are modified, I don't need loop anything.

What do you thing?

Answer

Please try this one. It will loop through original array, compare the value then put in correct position.

var array = [
              {value: 0.1, name: 'Mark'}, 
              {value: 0.3, name: 'Sonia'}
            ],
    new1 = {value: 0.2, name: 'John'},
    new2 = {value: 0.89, name: 'John1'},
    new3 = {value: 0.77, name: 'John2'};

console.log('original',array);

function pushSort(obj) {
  var i;
  for (i = 0; i < array.length; i++) {
    if (obj['value'] > array[i]['value'])
      continue;
    break;
  }
  //using splice to insert new element on specific position
  return array.splice(i,0,obj);  
}
pushSort(new1);
console.log('add', new1, array);

pushSort(new2);
console.log('add', new2, array);

pushSort(new3);
console.log('add', new3, array);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Comments