Closest Numeric Match

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to find the closest number from an array using JavaScript. We will use the Array.prototype.reduce() method and the Math.abs() function to compare the distance between each element in the array and a target value, returning the closest match. By the end of this lab, you will have a better understanding of how to implement this useful function in your JavaScript projects.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28198{{"`Closest Numeric Match`"}} javascript/arith_ops -.-> lab-28198{{"`Closest Numeric Match`"}} javascript/comp_ops -.-> lab-28198{{"`Closest Numeric Match`"}} javascript/higher_funcs -.-> lab-28198{{"`Closest Numeric Match`"}} end

A Function to Find the Closest Numeric Match in an Array

To find the closest number in an array, use the following function:

const closest = (arr, n) =>
  arr.reduce((acc, num) => (Math.abs(num - n) < Math.abs(acc - n) ? num : acc));

Here's how to use it:

  1. Open the Terminal/SSH.
  2. Type node.
  3. Use the closest() function and provide the array and the target value as arguments.

Example usage: closest([6, 1, 3, 7, 9], 5) will return 6, which is the closest number to 5 in the array.

Summary

Congratulations! You have completed the Closest Numeric Match lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like