Determine if the elements in an array are identical using the reduce() method

I'm looking to compare all values within a single array to determine if they are all equal or not. My current method is working correctly and providing the expected result.

var myArray1 = [50, 50, 50, 50, 50];  // all values are the same, should return true
var myArray2 = [50, 50, 50, 50, 51];  // last value differs, should return false

function compare(array) {
    var isSame = true;
    for(var i=0; i < array.length; i++) {
       isSame = array[0] === array[i] ? true : false;
    }
    return isSame;
}

console.log('compare 1:', compare(myArray1)); // true 
console.log('compare 2:', compare(myArray2)); // false

However, when I attempted the same comparison using reduce(), I seem to be misunderstanding how that function works. Both instances return false. Is there an obvious mistake in my approach? Can reduce() be used to achieve the desired result? If so, how should it be implemented?

var myArray1 = [50, 50, 50, 50, 50];
var myArray2 = [50, 50, 50, 50, 51];

console.log('reduce 1:', myArray1.reduce(
  function(a, b){
    return a === b ? true : false
  }
));

console.log('reduce 2:', myArray2.reduce(
  function(a, b){
    return a === b ? true : false
  }
));

Answer №1

reduce might not be the most suitable approach in this scenario. The value returned from one iteration is utilized as a in the subsequent iteration, and reduce does not terminate early.

If you prefer to utilize one of the array methods for this task, every could be a sensible option:

var myArray1 = [50, 50, 50, 50, 50];
var myArray2 = [50, 50, 50, 50, 51];

console.log('some 1:', myArray1.every(
  function(value, _, array){
    return array[0] === value;
  }
));

console.log('some 2:', myArray2.every(
  function(value, _, array){
    return array[0] === value;
  }
));

every stops processing as soon as the result is determined.

One could potentially force it into a reduce function, but it may not be the best fit. The approach involves initializing the flag with true and then combining the result by using the && operator while comparing the entry against the first element of the array:

var myArray1 = [50, 50, 50, 50, 50];
var myArray2 = [50, 50, 50, 50, 51];

console.log('some 1:', myArray1.reduce(
  function(flag, value){
    return flag && myArray1[0] === value;
  },
  true
));

console.log('some 2:', myArray2.reduce(
  function(flag, value){
    return flag && myArray2[0] === value;
  },
  true
));

Answer №2

To solve this problem, one common approach is to utilize the .every() method. Alternatively, you could implement a solution using the .reduce() function like so:

var arr = [50,50,50,50,50],
    brr = [50,50,51,50,50],
    res = arr.reduce((p,c) => p === c ? p : false);
console.log(res);
res = brr.reduce((p,c) => p === c ? p : false);
console.log(res);

This code snippet will output the element that is repeated throughout the array, or it will return false if there is an outlier value. Keep in mind that if your array consists solely of false values, this code will not work as intended.

Answer №3

Experiment with this approach if the values are numerical:

let firstArray = [10, 20, 30, 40, 50];
let secondArray = [10, 20, 30, 40, 51];

let comparison = firstArray >= secondArray && firstArray <= secondArray;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to retrieve the value of "id" using a "for...of" loop

I am seeking assistance with my auditTime function. In the loop using "for . . of", each element of the div HTML collection with the class name "time-block" should be iterated through, and the number value of that div's id should be assigned to the va ...

Create an array in JSON format that includes a JavaScript variable, with the variable's value changing each time a mouse

var question="What is your favorite color?"; var option="red"; var col=[]; When the user clicks, the variable value changes and values should be pushed in a specific format. I am new to JavaScript, please help me with this. Thank you. //On click, the var ...

Tips for accessing the value of a DOM node during the first render

I am attempting to extract a value from an input textbox during the initial rendering process using useRef, but I am encountering the following error: " ref is not a prop. Trying to access it will result in undefined being returned. If you need to ac ...

Communication between the Node development server and the Spring Boot application was hindered by a Cross-Origin Request

Here is the breakdown of my current setup: Backend: Utilizing Spring Boot (Java) with an endpoint at :8088 Frontend: Running Vue on a Node development server exposed at :8080 On the frontend, I have reconfigured axios in a file named http-common.js to s ...

What are the steps to rectify the issue of displaying data accurately on

I am working on my ReactJS project and using devextreme to create a unique circular gauge. However, I'm facing an issue where certain values are not being displayed correctly. For instance, instead of showing the value 5011480286.78, it is displaying ...

What is the best way to create a layout with two images positioned in the center?

Is it possible to align the two pictures to the center of the page horizontally using only HTML and CSS? I've tried using this code but it doesn't seem to work: #product .container { display: flex; justify-content: space-between; flex-w ...

Issues encountered with AngularJs filter search functionality

Why am I having trouble adapting this search filter from here? This is what my code looks like: controllers.js angular.module('starter.controllers', ['starter.services']) .controller('AppCtrl', function($scope, $ionicModal ...

Encountered issues loading JavaScript and received a pyppeteer error while trying to access a website through requests

I am facing a challenge when trying to scrape a webpage post login using BeautifulSoup and requests. Initially, I encountered a roadblock where the page requested JavaScript to be enabled to continue using the application. To work around this issue, I de ...

code, scripting - modal pop-up

My script currently has a popup window using window.open, but most browsers block this type of popups. I now want to change it to another popup that includes a php script, similar to what I've seen on other sites. It seems like they are using ajax. Ca ...

Leveraging Angular to retrieve images from Google Feed API

I'm currently working on developing an RSS reader and trying to integrate images from the Google Feed API. While I have successfully extracted the publishedDate and contentSnippet, I am facing difficulty in getting the image src. The code snippets bel ...

What is the best way to retrieve the JSON data from a POST request made through AJAX to a PHP file and save it in an array variable?

My ajax request sends JSON data to a PHP file named 'receive.php'. user_name , user_id, etc. are defined at the beginning of my script but can be changed to anything else. Below is the JavaScript code I am using: const data = { name: user_na ...

How to trigger an update of the useEffect() hook when a button is clicked

I am working with a functional component that contains a button and uses the "useEffect()" hook. My goal is to trigger a re-render of the component, updating the useEffect() hook when the button is clicked. const Emp_list = (props) => { useEffect(() ...

When velocity exceeds a certain threshold, collision detection may become unreliable

As I delve into detecting collisions between high-velocity balls, an obstacle arises. This issue seems to be quite common due to the nature of fast-moving objects colliding. I suspect that the solution lies within derivatives, and while I've drafted s ...

Gathering information in a non-blocking manner with $.ajax() in rails version 3.2.2

Currently, I am delving into the realm of asynchronous data retrieval in my Rails 3.2.2 project. As a newcomer to both JavaScript and jQuery, I've stumbled upon an issue where JavaScript is unable to fetch data from a different domain server. To overc ...

Arranging elements in an array with the help of functions

Struggling to decipher this code. Four additional functions are required aside from main(): one to read the array elements, one to print them, one to sort the array, and one to swap two elements of an array. No structured code can be used (e.g., no goto, ...

Performing AJAX requests within loops using Javascript can be a powerful tool

Utilizing jQuery to make an AJAX request and fetching data from a server. The retrieved data is then added to an element. The goal is for this process to occur 5 times, but it seems to happen randomly either 3, 4, or 5 times. Occasionally, the loop skips ...

Tips for handling alternate lines with two distinct styles in the Ace editor

I am looking to develop a unique note-taking editor using Ace. For instance, if I paste some Spanish text into the editor, I would like to add English words as notes for corresponding Spanish words. My goal is to display these English words above the resp ...

Getting information from MongoDB using Node.js and Angular

Currently, I am facing difficulty in retrieving data from MongoDB (I'm also using Mongoose) and sending it to Angular in order to populate the ng-repeat list with the retrieved data. I have managed to either display the data on a blank page directly f ...

Troubleshooting Type Conversion Error in ASP.NET MVC Controller

I have been working on an application that utilizes the following HTML and JavaScript. The user is required to input 5 props and then click on the 'Create' button. Subsequently, the JavaScript code compiles all of these props into a list before s ...

After moving a JavaScript application to heroku, the script appears to be nonfunctional

I developed a basic javascript application using mojs, an animation library, and aimed to host it on heroku. To begin with, I attempted the "heroku create" command to deploy the original app on heroku - although the app was accessible, the script did not f ...