ES5 Version:
var counts = [4, 9, 15, 6, 2],
goal = 5;
var closest = counts.reduce(function(prev, curr) {
return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});
console.log(closest);
More Related Contents:
- javascript slice without using built in method [closed]
- Array data to be filled into a table using JavaScript
- Sort out array of object using its value [duplicate]
- How do I check if an array includes a value in JavaScript?
- Short circuit Array.forEach like calling break
- Convert Array to Object
- Fastest way to duplicate an array in JavaScript – slice vs. ‘for’ loop
- Filter array of objects based on another array in javascript
- MongoDB, remove object from array
- Why does typeof array with objects return “object” and not “array”? [duplicate]
- How to initialize an array’s length in JavaScript?
- How can I access and process nested objects, arrays or JSON?
- Remove last item from array
- Check if object value exists within a Javascript array of objects and if not add a new object to array
- Obtain smallest value from array in Javascript?
- No semicolon before [] is causing error in JavaScript
- How do I remove objects from a JavaScript associative array?
- Filter strings in Array based on content (filter search value)
- How to merge multiple array of object by ID in javascript?
- How to convert an array of key-value tuples into an object
- Extract certain properties from all objects in array
- Checking for duplicate strings in JavaScript array
- Sort an array to have specific items first in the array
- Sort an array of objects by multiple properties
- Using setInterval() with a .map method in array and returning as a promise
- Lodash create collection from duplicate object keys
- JavaScript foreach loop on an associative array object
- Why can’t I check if an array is empty with array == []?
- javascript – find unique objects in array based on multiple properties
- How do I get the last 5 elements, excluding the first element from an array?