寻找一种方法来有效地确定不用作对象数组中任何对象的特定属性值的最小正整数。
换句话说,我正在寻找适用于这些数组的函数/算法:
var example1 = [{ id: 1 }, { id: 2 }, { id: 3 }],
example2 = [{ id: 6 }, { id: 4 }, { id: 2 }],
example3 = [{ id: 2 }, { id: 1 }, { id: 4, otherProp: 3 }];
将分别返回 4、1 和 3。 (在本例中显然使用了 id 属性。)
我考虑过使用 Underscore.js 来实现这一点,但我找不到一种没有一些丑陋的嵌套循环的方法。有人有更好的主意吗?
最佳答案
function next(prop) {
return function(arr) {
var used = arr.reduce(function(o, v) {
o[v[prop]] = true;
return o;
}, {});
for (var i=1; used[i]; i++);
return i;
}
}
var nextId = next("id");
nextId([{ id: 1 }, { id: 2 }, { id: 3 }]) // 4
nextId([{ id: 6 }, { id: 4 }, { id: 2 }]) // 1
nextId([{ id: 2 }, { id: 1 }, { id: 4, otherProp: 3 }]) // 3
关于javascript - 查找 javascript 对象数组中第一个未使用的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22715198/