Reputation: 156
How to find the most suitable number for a given number.
For example. I have a number 8 and an array of objects.
let num = 8;
let data = [
{ fist: {a: 1, b: 2}, second: {c: 11, d: 12}, number: 1 },
{ fist: {a: 3, b: 4}, second: {c: 13, d: 14}, number: 7 },
{ fist: {a: 5, b: 6}, second: {c: 15, d: 16}, number: 10 },
];
The closest number of all numbers in each object is 7. How can I display the whole obit to which the number 7 belongs?
Upvotes: 2
Views: 72
Reputation: 386604
You could reduce the array by choosing the item with the smaller absolute delta of given value and wanted value .
let num = 8,
data = [{ fist: { a: 1, b: 2 }, second: {c: 11, d: 12 }, number: 1 }, { fist: { a: 3, b: 4 }, second: { c: 13, d: 14 }, number: 7 }, { fist: { a: 5, b: 6 }, second: { c: 15, d: 16 }, number: 10 }],
result = data.reduce((a, b) =>
Math.abs(num - a.number) < Math.abs(num - b.number) ? a : b
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 28414
You can use .reduce
to get the obj with minimum distance from num
:
let num = 8;
let data = [
{ fist: {a: 1, b: 2}, second: {c: 11, d: 12}, number: 1 },
{ fist: {a: 3, b: 4}, second: {c: 13, d: 14}, number: 7 },
{ fist: {a: 5, b: 6}, second: {c: 15, d: 16}, number: 10 },
];
const _isEmpty = (obj) => Object.keys(obj).length === 0;
const objWithClosestNumber = data.reduce((acc, item) => {
if(_isEmpty(acc)) { return item };
const closestDist = Math.abs(num - acc.number),
currentDist = Math.abs(num - item.number);
acc = (currentDist < closestDist) ? item : acc;
return acc;
}, {});
console.log(objWithClosestNumber);
Upvotes: 2
Reputation: 3302
Traverse the array and find the smallest difference.
let num = 8;
let data = [
{ fist: { a: 1, b: 2 }, second: { c: 11, d: 12 }, number: 1 },
{ fist: { a: 3, b: 4 }, second: { c: 13, d: 14 }, number: 7 },
{ fist: { a: 5, b: 6 }, second: { c: 15, d: 16 }, number: 10 },
];
let diff = Math.abs(num - data[0].number);
let ret = data[0];
data.forEach((x) => {
if (diff > Math.abs(x.number - num)) {
diff = Math.abs(x.number - num);
ret = x;
}
});
console.log(ret);
Upvotes: 0