Javascript 对对象数组进行重新排序和筛选

Javascript 对对象数组进行重新排序和筛选,javascript,filter,Javascript,Filter,我正在寻找一种简单的方法,不仅可以对对象数组进行过滤,还可以对其进行重新排序,以便以正确的顺序对输出格式进行过滤和排序。下面是一个示例数组 [{ "id": "4", "fileName": "fileXX", "format": "mp3" }, { "id": "5", "fileName": "fileXY", "format": "aac" } }, { "id": "6", "fileName": "fileXZ", "format": "opu

我正在寻找一种简单的方法,不仅可以对对象数组进行过滤,还可以对其进行重新排序,以便以正确的顺序对输出格式进行过滤和排序。下面是一个示例数组

[{
  "id": "4",
  "fileName": "fileXX",
  "format": "mp3"
}, {
  "id": "5",
  "fileName": "fileXY",
  "format": "aac"
  }
}, {
  "id": "6",
  "fileName": "fileXZ",
  "format": "opus"
  }
}]
阵列可能更长,并且包含不同的格式,但目标是始终只允许mp3和aac,并让aac在阵列中排在第一位。这个例子的结果是

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

应避免按字母顺序排序,因为所需的顺序以后可能会更改。

您可以使用所需格式的对象进行筛选,并按所需的顺序进行排序

var data=[{id:“4”,文件名:“fileXX”,格式:“mp3”},{id:“5”,文件名:“fileXY”,格式:“aac”},{id:“6”,文件名:“fileXZ”,格式:“opus”},
顺序={aac:1,mp3:2},
结果=数据
.filter(({format})=>按顺序格式化)
.sort((a,b)=>order[a.format]-order[b.format]);
控制台日志(结果)

。作为控制台包装{max height:100%!important;top:0;}
您可以尝试以下方法:

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

您只需筛选相关格式,然后对结果集进行排序

var-arr=[
{
“id”:“4”,
“文件名”:“fileXX”,
“格式”:“mp3”
}, {
“id”:“5”,
“文件名”:“fileXY”,
“格式”:“aac”
}, {
“id”:“6”,
“文件名”:“fileXZ”,
“格式”:“作品”
}
]
var filteredar=arr.filter(item=>item.format===“mp3”| | item.format==“aac”)
filterDarr.sort(函数(a,b){
返回a.format>b.format
})

console.log(filteredar)
到目前为止您尝试了什么?好的,但是过滤和排序的
正确顺序是什么?用一种数组方法进行排序和筛选:谢谢你,尼娜。这绝对是一个非常灵活和可扩展的解决方案。