Javascript 按输入顺序对输出对象进行排序,避免O(n^2)
给定两个数组。我想按照输入中值的顺序对输出中的对象进行排序。结果应返回按输入数组中项目顺序排序的对象数组 注意:结果中可以有两个具有相同值的键的对象,最重要的是输入中项目的顺序Javascript 按输入顺序对输出对象进行排序,避免O(n^2),javascript,arrays,sorting,Javascript,Arrays,Sorting,给定两个数组。我想按照输入中值的顺序对输出中的对象进行排序。结果应返回按输入数组中项目顺序排序的对象数组 注意:结果中可以有两个具有相同值的键的对象,最重要的是输入中项目的顺序 const input = [ "app_id", "app_total", "app_name", "app_number", "app_date", "app_bank", "app_city", "total_tax", "t
const input = [
"app_id",
"app_total",
"app_name",
"app_number",
"app_date",
"app_bank",
"app_city",
"total_tax",
"total_paid",
"science_score",
"science_check"
]
结果应按输入顺序排序。样本结果如下:
const result = [{
app_id: 'APP-EBF02',
app_total: null,
app_name: null,
app_number: null,
app_date: '12/19/2019 19:28:18',
app_bank: null,
app_city: 'New York',
total_tax: 221.94000000000008,
total_paid: 168.7854,
science_score: '830.0000',
science_check: null
}, {
app_id: 'APP-4E0B2',
app_total: null,
app_name: null,
app_number: '3',
app_date: '12/20/2019 22:04:13',
app_bank: null,
app_city: 'New York',
total_tax: 299.64,
total_paid: 0,
science_score: '830.0000',
science_check: null
}, {
app_id: 'APP-77929',
app_total: null,
app_name: null,
app_number: 'e',
app_date: '12/23/2019 20:09:49',
app_bank: null,
app_city: 'New York',
total_tax: 110.70000000000003,
total_paid: 0,
science_score: '830.0000',
science_check: null
}]
这就是我想到的
function sorted(input, output){
const result = [];
const store = {};
input.forEach((res,index) => {
store[res] = index;
})
output.forEach((res) => {
Object.keys(res).forEach((el,i) => {
result[store[el]] = res[el]
})
})
return result;
}
console.log(sorted(input,output));
恐怕无法在一个对象中订购钥匙。订购对象键的目的是什么?是的,谢谢回复。基本上,我希望根据输入的内容保持结果的顺序。假设用户选择一个项目列表作为输入,然后在执行一些操作(表中的查询+自定义计算(已支付的税款、已支付的总额等))之后,将结果合并到一起,得到上述输出。我希望能够维护结果中输入的顺序
function sorted(input, output){
const result = [];
const store = {};
input.forEach((res,index) => {
store[res] = index;
})
output.forEach((res) => {
Object.keys(res).forEach((el,i) => {
result[store[el]] = res[el]
})
})
return result;
}
console.log(sorted(input,output));