Vincent Desrosiers
Vincent Desrosiers

Reputation: 170

.filter does not return object in correct order

I have an array of objects(suggestions) with ids and an array containing only ids(attributes). I need to make a new array with the objects from suggestions that have a similar id found in attributes.

suggestions: 

Name:"NAME_1"
Value:"16"
id:"295748b6-bf55-4225-add8-aaf000e4825a"


Name:"NAME_2"
Value:"something"
id:"68a65c6d-5a09-4e8a-8583-aaf000e4825a"

Name:"NAME_3"
Value:"4"
id:"69984329-eed1-47a2-8806-aaf000e4825a"

...

attributes:

attributes:Array[3]
0:"69984329-eed1-47a2-8806-aaf000e4825a"
1:"295748b6-bf55-4225-add8-aaf000e4825a"
2:"68a65c6d-5a09-4e8a-8583-aaf000e4825a"

function:

const chosenAttributes = this.suggestions.filter(
    item => this.attributes.includes(item.id)
    );
    this.chosenAttributes = chosenAttributes;

Output:

chosenAttributes:Array[3]
0:Object
Name:"NAME_1"
Value:"16"
id:"295748b6-bf55-4225-add8-aaf000e4825a"
1:Object
Name:"NAME_2"
Value:"something"
id:"68a65c6d-5a09-4e8a-8583-aaf000e4825a"
2:Object
Name:"NAME_3"
Value:"4"
id:"69984329-eed1-47a2-8806-aaf000e4825a"

This works however I need to have the objects in my new array(chosenAttributes) be in the same order that their ids appear in my attributes array. I'm not sure why they're not ordered correctly from the start.

Vue 2.6.11

Upvotes: 1

Views: 542

Answers (2)

flappix
flappix

Reputation: 2227

Array.filter does not change the order of the initial array, which is suggestions in your case. If you want a different order (order of the attributes array) you have to sort the new array in an extra step.

chosenAttributes.sort ( function (a, b)
{
    return this.attributes.indexOf (a.id) - this.attributes.indexOf (b.id);
});

Upvotes: 2

machineghost
machineghost

Reputation: 35795

It sounds like you just need to use Javascript's Array sort method:

const chosenAttributes = this.suggestions
  .filter(
    item => this.attributes.includes(item.id)
  )
  .sort(item => /* return 1, 0, or -1 to indicate sorting */);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort has further details.

Upvotes: 0

Related Questions