Helmi
Helmi

Reputation: 539

Reorder and filter Array of Objects

I'm looking for a simple way to not only filter but also reorder an array of objects so that that outcoming formats are filtered and sorted in the right order. Here's an example array

[{
  "id": "4",
  "fileName": "fileXX",
  "format": "mp3"
}, {
  "id": "5",
  "fileName": "fileXY",
  "format": "aac"
  }
}, {
  "id": "6",
  "fileName": "fileXZ",
  "format": "opus"
  }
}]

The array may be longer and contain different formats but the goal is to always only allow mp3 and aac and have aac come first in the array. Result for this example would be

[{
  "id": "5",
  "fileName": "fileXY",
  "format": "aac"
  }
},{
  "id": "4",
  "fileName": "fileXX",
  "format": "mp3"
}]

alphabetical sorting should be avoided as the desired order may change later.

Upvotes: 1

Views: 539

Answers (3)

Geeky
Geeky

Reputation: 7496

You can just filter for the associated formats and then sort on the result set

var arr = [
  {
  "id": "4",
  "fileName": "fileXX",
  "format": "mp3"
}, {
  "id": "5",
  "fileName": "fileXY",
  "format": "aac"
  }, {
  "id": "6",
  "fileName": "fileXZ",
  "format": "opus"
  }
]


var filteredArr= arr.filter(item=>item.format === 'mp3' || item.format ==='aac')



filteredArr.sort(function(a,b){
  return a.format > b.format
})

console.log(filteredArr)

Upvotes: 0

Arwandar
Arwandar

Reputation: 32

You could try something like this:

let myResult = array.filter(function(file) { 
    return file.format === 'mp3' || file.format === 'aac'
}).sort(function(a, b){
    if (a.format === b.format) return 0 // same order
    else if (a.format === 'aac') return -1 // a before b
    else return 1 // b before a
})

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

You could filter with an object of the wanted formats and sort it by the wanted order.

var data = [{ id: "4", fileName: "fileXX", format: "mp3" }, { id: "5", fileName: "fileXY", format: "aac" }, { id: "6", fileName: "fileXZ", format: "opus" }],
    order = { aac: 1, mp3: 2 },
    result = data
        .filter(({ format }) => format in order)
        .sort((a, b) => order[a.format] - order[b.format]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Related Questions