Home > Mobile >  How to sort particular array position based on the Id in Vuejs?
How to sort particular array position based on the Id in Vuejs?

Time:11-03

<div v-for="(item, index) in groups" 
:key="item.id" :id="item.id" 
class="group-name">
</div>

I Don't want to change all array values based on the ID. only specific position I want to change using ID.

I have done that logic using the below few line changes in the api call, like

     const first = data.groups_with_selected[7];
     const second = data.groups_with_selected[20];
     data.groups_with_selected.splice(2, 0, first, second);
     data.groups_with_selected.splice(9, 1)
     data.groups_with_selected.splice(21, 1)

with that, what i am trying to achieve finally i got it. But issue is, i cant expect the array value same all the time. So i have decided to re-arrange the array values based on the ID.

Out of all array values, I only want to change (7th position to 2nd position) and (21st position to 3rd position).

CodePudding user response:

orderMap would be your desired index outcome.

array would be your API response.

map orderMap with a function that finds the desired index and places it in our sorted array.

const orderMap = ['third', 'second', 'first'];

const array = [{name: 'first'}, {name: 'second'}, {name: 'third'}];

let sorted = orderMap.map(function(sortBy){
  return this.find(function(toSort){return toSort.name === sortBy})
}, array)

console.log(sorted);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

// as method -> Result is your response Data. OrderMap the map to order by. 
sortResultSet(result, orderMap) {
  return orderMap.map(function(sortBy){
    return this.find(function(toSort){return toSort.name === sortBy})
  }, result)
}

CodePudding user response:

You could write a custom sorting function so it sorts them according to your needs. For eg:

function Sort(item1, item2){
  if (item1.name > item2.name)
    return 1;
  else if (item1.name < item2.name)
    return -1;
  else 
    return 0;
}

And then call it on the array

array.sort(Sort);
console.log(array);

If you want to you can omit the function declaration and just pass function as a parameter.

array.sort(function (item1, item2) {
  <same code from above>
});

And then just add it to the desired object from Vue

  • Related