Identify if all characters are equal

Asked

Viewed 1,246 times

9

I have the following code that works perfectly.

In it I possess a string and check whether all of its characters are equal or not:

var numbers = '1111121111',
    firstNumber = numbers.substr(0,1),
    numbersEquals = true;

for(let i = 1; i < numbers.length; i++) {
  if (numbers[i] != firstNumber) numbersEquals = false;
}
console.log('numbersEquals = ' + numbersEquals)

There is an easier way or a ready method to do this?

I think I’m using too much code to do something simple.

4 answers

8

With ECMA6, it is possible using Set:

const unicos = [...new Set(numbers)]

Example:

var numbers = '1111112111';

if (new Set(numbers).size > 1)
  console.log("Todos os valores não são iguais");
else
  console.log("Todos os valores são iguais");

Edit:

As @bfavaretto suggested, it is possible to get the number element in Set object.

  • @Lucas does not know this notation yet '[...new Set(Numbers)]'

  • @Lan now you know :)

  • 1

    @There are two things there, if you want to research: the Set, and the Operator spread ....

  • thanks @Lucascosta! :)

  • I’m giving a studied at this now @bfavaretto worth! ;)

8

There are many ways to do this. I don’t think yours is wrong, it’s very clear and didactic. But it has shorter ways, like Mr Felix’s. Converting to array can do some tricks too, for example:

var numbers = '1111121111';
numbers.split('').every(function(num, i, arr) { return num == arr[0] }); // false

Or even shorter in ES-2015:

const numbers = '1111121111';
[...numbers].every( (num, i, arr) => num == arr[0] ); // false

7


Using RegExp.prototype.test(), do the following:

/^(.)\1+$/.test(sua_string)

This returns true or false depending on whether all characters are equal or not.

/^(.)\1+$/.test("xxxx"); // true
/^(.)\1+$/.test("xxxy"); // false

test() is since the ECMA 3rd Edition (1999). It will basically work on all browsers.

  • 1

    Good! I didn’t know this Method! :)

5

I would do exactly what you did because it should be the fastest solution. But there are several alternatives, one of them:

var numbers = '1111121111';
console.log('numbersEquals = ' + (numbers.replace(new RegExp(numbers.substr(0, 1), 'g'), "").length == 0));
numbers = '1111111111';
console.log('numbersEquals = ' + (numbers.replace(new RegExp(numbers.substr(0, 1), 'g'), "").length == 0));

I put in the Github for future reference.

  • This return the amount of occurrences of Regexp I n knew. I think this will still be useful to me for other situations! ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.