0

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
        }
    }
}
}
BBB_TOAD
  • 49
  • 7
  • 1
    [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Aug 18 '22 at 05:09
  • Move the first if to after the loop. – SuperStormer Aug 18 '22 at 05:11

3 Answers3

0

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
TesterPY
  • 13
  • 3
0

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 }
A1exandr Belan
  • 4,442
  • 3
  • 26
  • 48
-1

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
Kordrad
  • 1,154
  • 7
  • 18
  • There you can find more my solutions https://stackoverflow.com/questions/7376598/in-javascript-how-do-i-check-if-an-array-has-duplicate-values/70782513#70782513 – Kordrad Aug 18 '22 at 05:44