I'd define it like so:
function getFields(length) {
var d = data
.filter(d => d.length <= length) // get the list of matching objects
.sort((a, b) => b.length - a.length) // sort descending so largest value is at the front of the array
.shift(); // get the first element from the array
return (d !== undefined) ? d.fields : undefined;// if that element exists, return .fields, otherwise undefined
}
In action:
var data = [{
length: 900,
fields: 3
},{
length: 1150,
fields: 4
},{
length: 1700,
fields: 5
}];
function getFields(length) {
var d = data
.filter(d => d.length <= length) // get the list of matching objects
.sort((a, b) => b.length - a.length) // sort descending so largest value is at the front of the array
.shift(); // get the first element from the array
return (d !== undefined) ? d.fields : undefined;// if that element exists, return .fields, otherwise undefined
}
var tests = [1700, 1150, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700];
console.log(tests.map(getFields));
While I don't know if this is performant enough for your current use case, but it's relatively readable and easy-to-follow (although this could be made more efficient if the data were always ordered by length, for instance). If you need something more performant, you could do something like this instead:
function getFields(length) {
let d;
let i = data.length - 1;
while (i > -1 && d === undefined) {
if (data[i].length <= length) {
d = data[i].fields;
}
i -= 1;
}
return d;
}
In action:
var data = [{
length: 900,
fields: 3
},{
length: 1150,
fields: 4
},{
length: 1700,
fields: 5
}];
function getFields(length) {
let d;
let i = data.length - 1;
while (i > -1 && d === undefined) {
if (data[i].length <= length) {
d = data[i].fields;
}
i -= 1;
}
return d;
}
var tests = [1700, 1150, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700];
console.log(tests.map(getFields));
length?