Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move element to first position in array

I have an object like this:

var data = [
    { id: "fmgbwe45", age: 24, gender: "male"   },
    { id: "kjregh23", age: 27, gender: "female" }, 
    { id: "kjfdhg87", age: 30, gender: "male" }, 
    { id: "lsdjfk43", age: 10, gender: "female" }, 
]

I want to sort the object, this is my expected output:

var data = [
    { id: "kjfdhg87", age: 30, gender: "male" },  //only one record will match in my sort
    { id: "fmgbwe45", age: 24, gender: "male"   },
    { id: "kjregh23", age: 27, gender: "female" }, 
    { id: "lsdjfk43", age: 10, gender: "female" }, 
]

I have tried this:

$scope.sort_by = function (newSortingOrder) {
    var stringToFilter = newSortingOrder.toString();   //this holds 'kjfdhg87'
    var obj = data.sort(function(o) { return o.id - stringToFilter; });
    var finalObj = [obj];
    sortedData = finalObj;
    console.log(sortedData ); //sorting is not working as expected where im doing wrong.
}
like image 881
Mr world wide Avatar asked May 05 '18 05:05

Mr world wide


People also ask

How do you move an element from an array to first position?

To change the position of an element in an array:Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.

How do you move an element in an array?

Create a temp variable and assign the value of the original position to it. Now, assign the value in the new position to original position. Finally, assign the value in the temp to the new position.

How do you push something to the first array?

Adding new elements at the beginning of existing array can be done by using Array unshift() method. This method is similar to push() method but it adds element at the beginning of the array.

How do you select the first element of an array?

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more. We will discuss the different ways to access the first element of an array sequentially.


1 Answers

Since you are just moving one item to the top, I will just use splice() and unshift() the item:

var data = [
    { id: "fmgbwe45", age: 24, gender: "male"   },
    { id: "kjregh23", age: 27, gender: "female" }, 
    { id: "kjfdhg87", age: 30, gender: "male" }, 
    { id: "lsdjfk43", age: 10, gender: "female" }, 
]
data.forEach(function(item,i){
  if(item.id === "kjfdhg87"){
    data.splice(i, 1);
    data.unshift(item);
  }
});

console.log(data);
like image 158
Mamun Avatar answered Sep 28 '22 23:09

Mamun