Find the number in an array that is closest to a given number

后端 未结 7 756
温柔的废话
温柔的废话 2021-01-03 23:07

I have an Array of integers in javascript, [5,10,15,20,25,30,35] when given a number x, how can I find the element in the array that is closest to that number?

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-03 23:41

    function getClosest(array, target) {
        var tuples = _.map(array, function(val) {
            return [val, Math.abs(val - target)];
        });
        return _.reduce(tuples, function(memo, val) {
            return (memo[1] < val[1]) ? memo : val;
        }, [-1, 999])[0];
    }
    

    If using a functional approach is applicable then you can map the set to tuples of (value, distance) then reduce that set of tuples to the tuple with the smallest distance. We return the value in that tuple.

    To explain the useage of _.map. You map all the values in your array to new values and the function will return the array of new values. In this case an array of tuples.

    To explain the useage of _.reduce. You reduce the array to a single value. You pass in an array and a memo. The memo is your "running counter" as you move through the array. In this case we check whether the current tuple is closer then the memo and if so make it the memo. We then return the memo at the end.

    The code snippet above relies on underscore.js to remove the nitty gritty of functional style javascript

提交回复
热议问题