Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
var findClosest = function (x, arr) {
  var indexArr = arr.map(function(k) { return Math.abs(k - x); })
  var min = Math.min.apply(Math, indexArr)
  return arr[indexArr.indexOf(min)]
}
var demoArr = [5, 10, 15, 20, 25, 30, 35]
console.log(findClosest(-1, demoArr))
console.log(findClosest(5, demoArr))
console.log(findClosest(7, demoArr))
console.log(findClosest(8, demoArr))
console.log(findClosest(12, demoArr))
console.log(findClosest(13, demoArr))
console.log(findClosest(19, demoArr))
console.log(findClosest(24, demoArr))
console.log(findClosest(45, demoArr))
console.log('Not sorted: ');
var demoArr2 = [10, 5, 20, 35, 25, 30, 15]
console.log(findClosest(-1, demoArr))
console.log(findClosest(5, demoArr))
console.log(findClosest(7, demoArr))
console.log(findClosest(8, demoArr))
console.log(findClosest(12, demoArr))
console.log(findClosest(13, demoArr))
console.log(findClosest(19, demoArr))
console.log(findClosest(24, demoArr))
console.log(findClosest(45, demoArr))
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
danmindrupro
0viewers