我有一个数组名称JSON,以及如何检查每个部门的薪水并找到薪水最高的部门
var json = [
{
id: 1,
name: 'BInit',
salary: 20000,
department_slug: "it",
department: 'IT'
},
{
id: 2,
name: 'BaaaInit',
salary: 25000,
department_slug: "hr",
department: 'HR'
},
{
id: 3,
name: 'At',
salary: 15000,
department_slug: "finance",
department: 'FInance'
},
{
id: 4,
name: 'aas',
salary: 35000,
department_slug: "finance",
department: 'FInance'
}
];
我会尝试
for(var i=0; i<json.length; i++){
for (var j= i; j<json.length; j++){
}
}
我需要这个数组中最高薪的部门
答案 0 :(得分:0)
编辑:我意识到我并没有完全理解原来的问题:找到薪水最高的部门
我更改了代码以查找薪水最高的部门(因为可能有多个部门拥有相同的薪水总额
请注意,我认为属性 department_slug 充当唯一ID。
var json = [
{
id: 1,
name: 'BInit',
salary: 20000,
department_slug: "it",
department: 'IT'
},
{
id: 2,
name: 'BaaaInit',
salary: 25000,
department_slug: "hr",
department: 'HR'
},
{
id: 3,
name: 'At',
salary: 15000,
department_slug: "finance",
department: 'FInance'
},
{
id: 4,
name: 'aas',
salary: 35000,
department_slug: "finance",
department: 'FInance'
}
];
var depTotalSalaries = {};
for(var i=0; i<json.length; i++) {
if (!depTotalSalaries[json[i].department_slug]) {
depTotalSalaries[json[i].department_slug] = json[i].salary;
} else {
depTotalSalaries[json[i].department_slug] += json[i].salary;
}
}
var maxSalary = 0;
var departments = Object.keys(depTotalSalaries);
for(var i=0; i<departments.length; i++){
maxSalary = Math.max(maxSalary, depTotalSalaries[departments[i]])
}
for(var i=0; i<departments.length; i++){
if (depTotalSalaries[departments[i]] == maxSalary) {
console.log(departments[i], maxSalary);
}
}
答案 1 :(得分:0)
我会做的是这样的:
<Steps direction="vertical" current={1}>
<Step title="Finished" icon={1} description="This is a description." />
<Step title="In Progress" icon={2} description="This is a description." />
<Step title="Waiting" icon={3} description="This is a description." />
</Steps>
来源: https://flaviocopes.com/how-to-sort-array-of-objects-by-property-javascript/
答案 2 :(得分:-1)
在下面的示例中使用array.reduce
var json = [
{
id: 1,
name: 'BInit',
salary: 20000,
department_slug: "it",
department: 'IT'
},
{
id: 2,
name: 'BaaaInit',
salary: 25000,
department_slug: "hr",
department: 'HR'
},
{
id: 3,
name: 'At',
salary: 15000,
department_slug: "finance",
department: 'FInance'
},
{
id: 4,
name: 'aas',
salary: 35000,
department_slug: "finance",
department: 'FInance'
}
];
const max = json.reduce(function(old, item) {
return (old.y > item.y) ? old : item
})
console.log('max', max.salary);
答案 3 :(得分:-1)
更老套的方法:按薪水排序,然后从排序列表中选择第一个元素:
var json = [
{
id: 1,
name: 'BInit',
salary: 20000,
department_slug: "it",
department: 'IT'
},
{
id: 2,
name: 'BaaaInit',
salary: 25000,
department_slug: "hr",
department: 'HR'
},
{
id: 3,
name: 'At',
salary: 15000,
department_slug: "finance",
department: 'FInance'
},
{
id: 4,
name: 'aas',
salary: 35000,
department_slug: "finance",
department: 'FInance'
}
];
var sorted = json.sort((a, b) => a.salary > b.salary ? -1 : 1)
// sorted[0] is the highest salary
请注意,Array.sort
会更改源,因此,如果您关心列表的原始排序,请不要使用此方法。