1

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.

3
  • What have you tried so far? Commented May 15, 2018 at 14:56
  • ok but what is the right order for filtering and sorting Commented May 15, 2018 at 14:58
  • May I interest you in the almighty reduce method? Sort and filter with one array method: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented May 15, 2018 at 15:02

3 Answers 3

2

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; }

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, Nina. This is definitely a very flexible and extendable solution.
1

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
})

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.