Jak*_*ern 4 javascript average
我对 javascript 很陌生,正在处理 leetcode 中的问题。
包含的描述是:“给定一个唯一整数salary数组,其中salary[i]是雇员i的工资。
返回不包括最低和最高工资的员工平均工资。”
当我运行我的代码时,它说传入以下数组时输出不正确。
[25000,48000,57000,86000,33000,10000,42000,3000,54000,29000,79000,40000]
Expected Output: 41700.00000
My Output: 41000.00000
Run Code Online (Sandbox Code Playgroud)
我已经将我的代码与其他提交的代码进行了比较,据我所知,我的代码应该运行相同。这是我的代码:
[25000,48000,57000,86000,33000,10000,42000,3000,54000,29000,79000,40000]
Expected Output: 41700.00000
My Output: 41000.00000
Run Code Online (Sandbox Code Playgroud)
感谢您对此有任何了解。
您按字母顺序排列数组,而不是按最小数字排序,因此最终会删除错误的数字。
使用sort((a, b) => a - b)来代替:
const salary = [25000,48000,57000,86000,33000,10000,42000,3000,54000,29000,79000,40000]
function average(salary) {
var sortedSalary = salary.sort((a, b) => a - b);
var total = sortedSalary.reduce((curr, acc) => { return curr + acc }, 0);
var result = (total - sortedSalary[0] - sortedSalary[sortedSalary.length - 1]) / (sortedSalary.length - 2);
return result;
};
console.log(average(salary))Run Code Online (Sandbox Code Playgroud)