考虑以下目标:
// Example 1
{
gradeA: 100,
gradeB: 'No-Data',
gradeC: 'No-Data'
}// Example 2
{
gradeA: 50,
gradeB: 40,
gradeC: 'No-Data'
}// Example 3
{
gradeA: 75,
gradeB: 'No-Data',
gradeC: 'No-Data'
}它们代表一个百分比,即所有三个职等的总和都是100。当可以计算键的值时,我们如何使用'No-Data'插值键?
预期成果:
// Example 1
{
gradeA: 100,
gradeB: 0,
gradeC: 0
}// Example 2
{
gradeA: 50,
gradeB: 40,
gradeC: 10
}// Example 3
{
gradeA: 75,
gradeB: 'No-Data',
gradeC: 'No-Data'
}
// Note: This one can't be figured out so we leave it as is.我的伪代码解决方案:
function interpolate(obj) {
// If only one key is a number:
// The value is 100:
// Set the other two keys to 0 and return the obj.
// The value is less than 100:
// return obj unchanged.
// If only one key is not a number:
// set that key to the sum of the two numbers minus 100 and return the obj.
}这里有两个主要问题:
如何找出'No-Data'.
在现实中,这些对象在数组中,但我相信我可以自己解决这个问题。
发布于 2021-10-01 20:32:06
您可以使用类似于No-Data).的
let keys = Object.keys(obj).filter(k=>obj[k]===value);
只需数一数数组中的项目数,就可以查看您有多少项。
No-Data发生次数时的效率。提示:如果您想尽可能提高效率,那么在找到2:) No-Data 之后,您就不需要继续查找出现的了。
Ps。发布的其他代码有几个问题,如果您提交:),可能会阻止您获得满分:)
发布于 2021-10-01 20:30:07
使用您所描述的相同的逻辑:
function interpolate(obj) {
var noData = 0;
Object.keys(obj).forEach(key => {
if (isNaN(obj[key])) {
noData++;
}
});
var sum = 0;
var missingKey;
if (noData == 1) {
Object.keys(obj).forEach(key => {
if (!isNaN(obj[key])) {
sum += obj[key];
} else {
missingKey = key;
}
});
obj[missingKey] = 100 - sum;
return obj
}
return obj;
}
var objects = [{
gradeA: 100,
gradeB: 'No-Data',
gradeC: 'No-Data'
}, {
gradeA: 50,
gradeB: 40,
gradeC: 'No-Data'
}, {
gradeA: 75,
gradeB: 'No-Data',
gradeC: 'No-Data'
}]
objects.forEach(o => console.log(interpolate(o)));
发布于 2021-10-01 20:51:32
在我的解决方案中,我分析每个对象的分数和无数据值的总和。然后,如果条件匹配,我将继续替换每个对象的每个属性中的无数据值。适用于任意数量的年级。
const objects = [{
gradeA: 100,
gradeB: 'No-Data',
gradeC: 'No-Data'
}, {
gradeA: 50,
gradeB: 40,
gradeC: 'No-Data'
}, {
gradeA: 75,
gradeB: 'No-Data',
gradeC: 'No-Data'
}];
const analysis = objects
.map( o => Object.values(o)
.reduce( ([o, sum, nodatacount], v) =>
v==='No-Data'
? [o, sum, nodatacount+1]
: [o, sum+v, nodatacount],
[o, 0, 0] ) );
for(const [o, sum, nodatacount] of analysis) {
if(sum === 100 || nodatacount === 1) {
for(const [key, _] of Object.entries(o)
.filter(([_, value]) => value==='No-Data')
) {
o[key] = 100-sum;
}
}
}
console.log( objects );.as-console-wrapper {top:0; max-height: 100% !important}
https://stackoverflow.com/questions/69411593
复制相似问题