Checking Array Equality with Mapping Function

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will be exploring how to check if all elements in an array are equal based on a provided mapping function using JavaScript. We will be using the allEqualBy function that applies the mapping function to the first element of the array and uses Array.prototype.every() to compare the rest of the elements to the first one. This lab is designed to help you understand the concept of mapping functions and how they can be used to compare elements in an array.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28324{{"`Checking Array Equality with Mapping Function`"}} javascript/data_types -.-> lab-28324{{"`Checking Array Equality with Mapping Function`"}} javascript/arith_ops -.-> lab-28324{{"`Checking Array Equality with Mapping Function`"}} javascript/comp_ops -.-> lab-28324{{"`Checking Array Equality with Mapping Function`"}} javascript/array_methods -.-> lab-28324{{"`Checking Array Equality with Mapping Function`"}} end

Checking if Array Elements Are Equal with a Given Function

To check if all elements in an array are equal, use the allEqualBy function. This function applies a given mapping function fn to the first element of the array arr. It then checks if fn returns the same value for all elements in the array as it did for the first element, using Array.prototype.every(). The function uses the strict comparison operator, which does not account for NaN self-inequality.

Here's the code for allEqualBy:

const allEqualBy = (arr, fn) => {
  const eql = fn(arr[0]);
  return arr.every((val) => fn(val) === eql);
};

You can use allEqualBy like this:

allEqualBy([1.1, 1.2, 1.3], Math.round); // true
allEqualBy([1.1, 1.3, 1.6], Math.round); // false

To start practicing coding with this function, open the Terminal/SSH and type node.

Summary

Congratulations! You have completed the Check if Array Elements Are Equal Based on Function lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like