寻找一种有效确定最低正整数的方法,该正整数不用作对象数组中任何对象中特定属性的值.
换句话说,我正在寻找一个针对这些数组的函数/算法:
var example1 = [{ id: 1 }, { id: 2 }, { id: 3 }],
example2 = [{ id: 6 }, { id: 4 }, { id: 2 }],
example3 = [{ id: 2 }, { id: 1 }, { id: 4, otherProp: 3 }];
Run Code Online (Sandbox Code Playgroud)
将分别返回4,1和3.(显然在本例中使用了id-property.)
我考虑过使用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
Run Code Online (Sandbox Code Playgroud)