Home > database >  Function is not returning variables. Javascript. (Boolean)
Function is not returning variables. Javascript. (Boolean)

Time:08-18

I am trying to create a function which can check whether all the items in the list given are the same or not. But in the end it doesn't return anything but undefined. Please help. What am I doing wrong here.

function check(list) {

let number = 0;
if (number == list.length) {
    return true;
} else {
    for (let l = 0; l < list.length; l  ) {
        if (list[0] != list[l]) {
            return false;
        }
        else {
            number  = 1
        }
    }
}
}

CodePudding user response:

You need one more line below the for loop. You code gave a return value when 1 or more of the list items are different, however when all the items are the same, there was no return value.

if (number == list.length) {
        return true;
    } else {
        for (let l = 0; l < list.length; l  ) {
            if (list[0] != list[l]) {
                return false;
            }
            else {
                number  = 1
            }
        }
        return true; // This is what you need

CodePudding user response:

I prefer to use solution with new Set function.

function check(list = []) {
  const uniqueArr = new Set(list.map(JSON.stringify));
  return uniqueArr.size === 1;
}

console.log(check([1, 2, 1]));              // false
console.log(check([1, 1, 1]));              // true
console.log(check([{a:1}, {a:1}, {a:1}]));  // true
console.log(check([{a:2}, {a:1}, {a:1}]));  // false

Steps how the code works:

  1. list.map(JSON.stringify) convert all elements to string. (safe solution for object, arrays etc.)
  2. new Set(...) remove duplicated elements
  3. uniqueArr.size === 1 if we have more unique elements in array than 1 then return false

CodePudding user response:

In this case it is better to use .every

const check = (list) => list.every((e) => e === list[0]);

console.log(check(['a', 'a', 'a', 'a']));  // true
console.log(check(['a', 'a', 'a', 'b']));  // false
console.log(check([]));                    // true
.as-console-wrapper { max-height: 100% !important; top: 0 }

  • Related