Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value from forEach [duplicate]

I'm really new to JavaScript, and I've encountered a problem that I don't understand.

I wanted to write function which takes an array as an argument, and returns true if all elements in the array are identical.

By now I know that a simple for loop is more effective, but I wanted to do this simple function with forEach().

function isUniform(array) {
    let uniChecker = array[0];
    array.forEach(function(element) {
        if (uniChecker !== element) {
            return false;
        }
    });
    return true;
}

It always returns true, even if it should return false.

like image 677
Zopy Avatar asked May 14 '19 11:05

Zopy


People also ask

Can foreach return a value?

The forEach() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order. Unlike map() , forEach() always returns undefined and is not chainable.

Does foreach make a copy?

Summary. To summarize: foreach will copy the array structure if and only if the iterated array is not referenced and has a refcount > 1. foreach will additionally copy the array values if and only if the previous point applies and the iteration is done by reference.

Can we use nested foreach?

An important feature of foreach is the %:% operator. I call this the nesting operator because it is used to create nested foreach loops. Like the %do% and %dopar% operators, it is a binary operator, but it operates on two foreach objects.

Can we use foreach instead of for loop?

The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.


2 Answers

Unfortunately returning from the forEach callback does nothing to the outer scope, it simply exits the callback scope. While forEach can be used it's not the most efficient as there's no real way of exiting the loop early.

Better alternatives would be every / some, these functions are designed to test items in an array and detect anomalies (determined by whatever condition you provide) and exit on the first mismatch e.g.

const isUniform = arr => arr.every(x => arr[0] === x)

Playground

const arr = [1,1,3,1,1,2]
// using `every` (recommended)
console.log(`Using 'every'...`);
let isUniform = arr => arr.every(x => {
  console.log(`Testing ${x}`);
  return arr[0] === x;
});
console.log(isUniform(arr));
// using `some` (bit more complicated but can still work)
console.log(`Using 'some'...`);
isUniform = arr => !arr.some(x => {
  console.log(`Testing ${x}`);
  return arr[0] !== x;
});
console.log(isUniform(arr));
like image 142
James Avatar answered Sep 23 '22 18:09

James


forEach() throws away return values and always returns undefined

so no matter what you do inside your code the return value from forEach is never returned

You can create a flag that sets to false when your condition is met(Its a suggestion if you want to go with ForEach)

function isUniform(array) {
 let flag=true;
    let uniChecker = array[0];
    array.forEach(function(element) {
        if (uniChecker !== element) {
          flag=false;
        }
    });
    return flag;
}
like image 32
Shubh Avatar answered Sep 26 '22 18:09

Shubh