algorithmicCoder
algorithmicCoder

Reputation: 6789

How to find the closest array element to another array element x where y is closer if it is after x in the array?

EDIT: So I want a function that takes in an array e.g. ['foo',2,'bar',4,5] and an element e.g. 'bar' and returns the closest element. In this case it should return 4 (as opposed to 2 because 4 is after 'bar').

Whats a simple way to do this?....looking for something that uses a functional style like underscore.js...

I know i can do it the brute force way (iteration) but wondering if there's a clever way (like mod size of array math) that makes this one or two lines.

Upvotes: 0

Views: 88

Answers (1)

Mike Edwards
Mike Edwards

Reputation: 3771

How about:

function closest(arr, val) {
    var idx = arr.indexOf(val);
    if(idx < 0 || arr.length === 1) { return null; }
    return (idx+1) < arr.length ? arr[idx+1] : arr[idx-1]
}

Upvotes: 2

Related Questions