如何从对象排序数组? 代码:
let A = [ { text: '故事', value: 'story', },
{ text: '诗歌', value: 'poetry', },
{ text: '励志', value: 'inspirational', }
];
// array B from backend**
let B = {
story: 2,
poetry: 34,
inspirational: 30,
};
我想要这个:
[
{ text: '诗歌', value: 'poetry', },
{ text: '励志', value: 'inspirational'},
{ text: '故事', value: 'story', },
];
答案 0 :(得分:3)
只需使用JavaScript sort函数。
注意::对数字进行排序时,您可以简单地使用紧凑比较:
紧凑比较: myArray.sort((n1,n2)=> n1-n2);
let A = [ { text: '故事', value: 'story', },
{ text: '诗歌', value: 'poetry', },
{ text: '励志', value: 'inspirational', }
];
// array B from backend**
let B = {
story: 2,
poetry: 34,
inspirational: 30,
};
A.sort((a, b) => B[b.value]-B[a.value] );
console.log(A);
答案 1 :(得分:2)
您可以在$reference = Import-Csv -Path D:\corpold.csv
$lookup = $reference | Group-Object -AsHashTable -AsString -Property EMPID
$results = Import-Csv -Path D:\corpnew.csv | foreach {
$email = $_.EMAIL_ADDRESS
$status = $_.ACTIVE
$fs = $_.FIRST_NAME
$ls = $_.LAST_NAME
$id = $_.EMPID
$title = $_.JOB_TITLE
$code = $_.JOB_CODE
$type = $_.USER_TYPE
$designee = $_.DESIGNEE
$stores = $_.STORES
$hiredate = $_.HIRE_DATE
$dept = $_.DEPARTMENT
$grp = $_.GROUP
if ($lookup.ContainsKey($id)) {
# if exists in yesterdays file
# trying to figure out how to compare and only provide results into
# the Export-Csv that have changed while excluding any items in
# corpold that do not exist in corpnew
} else {
# if it does not exist update all fields
[PSCustomObject]@{
ACTIVE = $status
EMAIL_ADDRESS = $email
FIRST_NAME = $fs
LAST_NAME = $ls
EMPID = $id
JOB_TITLE = $title
JOB_CODE = $code
USER_TYPE = $type
DESIGNEE = $designee
STORES = $stores
HIRE_DATE = $hiredate
DEPARTMENT = $dept
GROUP = $grp
}
}
}
# Sample outputs
$results
$results | Export-Csv -Path D:\delta.csv -NoTypeInformation
中使用箭头功能作为自定义比较器。反向排序是通过索引array.sort
对象以检索比较元素的排序值并从B
中减去a
的值来完成的。
b
答案 2 :(得分:2)
您可以使用let A = [
{ text: '故事', value: 'story', },
{ text: '诗歌', value: 'poetry', },
{ text: '励志', value: 'inspirational', }
];
let B = {
story: 2,
poetry: 34,
inspirational: 30,
};
const sorted = A.sort((a, b) => B[b.value] - B[a.value]);
console.log(sorted);
来排列数组元素。如果sort()
上不存在value
,则可以使用Number.NEGATIVE_INFINITY
作为默认值。这会将未定义的值放在最后。
B
答案 3 :(得分:1)
尝试一下,它使用箭头功能和let A = [{"text":"诗歌","value":"poetry"},{"text":"励志","value":"inspirational"},{"text":"故事","value":"story"}];
let B = {"story":2,"poetry":34,"inspirational":30};
A.sort((x, y) => (B[y.value] || Number.NEGATIVE_INFINITY) - (B[x.value] || Number.NEGATIVE_INFINITY));
console.log(A);
:
array.sort
答案 4 :(得分:0)
使用功能Array.prototype.sort
,可以完成所需的输出。
此B[bV] - B[aV]
将返回小于0
或大于0
或等于0
的值,这是函数sort
期望得到的值根据对象B
中的值将元素定位在特定索引处。
let A = [{ text: '故事', value: 'story', }, { text: '诗歌', value: 'poetry', }, { text: '励志', value: 'inspirational', }],
B = { story: 2, poetry: 34, inspirational: 30};
A.sort(({value: aV}, {value: bV}) => B[bV] - B[aV]);
console.log(A);
.as-console-wrapper { max-height: 100% !important; top: 0; }