2

I have a list of strings and nulls. Now I want to check if all strings in the list are the same and nulls should be ignored. So for instance

  • [null, "a", "a", null, "a"] should evaluate to true, because all strings are equal
  • [null, "a", "a", null, "b"] should evaluate to false, because there is "b" and "a"

There are other questions on SO that are concerned with finding duplicates or equal values, but none of them seem to consider null values.

I already thought about implementing this with

  • a loop where I would save the first string and then compare to it in the later iterations
  • a filter followed by every

However I was wondering if there is a better more intuitive way to do this.

6
  • 3
    Maybe new Set(array.filter((value) => value !== null)).size <= 1? Commented Jun 15, 2023 at 10:31
  • no need to iterate every, can exit early with some Commented Jun 15, 2023 at 11:26
  • @SebastianSimon Please submit your comment as an answer. Commented Jun 15, 2023 at 11:33
  • @Philipp gog’s idea is even better. Commented Jun 15, 2023 at 11:35
  • @SebastianSimon I have seen his answer. Please submit yours as well, so I can accept it as an answer, if I decide that I like it more. Commented Jun 15, 2023 at 11:39

2 Answers 2

3

You could do something like

set = new Set(yourArray)
set.delete(null)
if (set.size === 1)
   // unique
Sign up to request clarification or add additional context in comments.

Comments

1
  • a loop where I would save the first string and then compare to it in the later iterations
  • a filter followed by every

you can do it with an empty variable followed by every:

let j; // first non null value
const result = array.every((v,i,a) => v === null || v === a[j??=i]) && j != null;

Edit: OK, let's take this apart:

  • every((v,i,a) => v === null || ...) check that every element is either null or ...
  • so v === a[j??=i] is only executed when v is not null
  • j ??= i is basically a shorthand for j === null || j === undefined ? (j = i) : j so j will adapt the first i where v !== null
  • but our loop doesn't differentiate between array.every((v,i,a) => v === null) and array.every((v,i,a) => v === a[j??=i]) so we also want to check that v === a[j??=i] was executed at least once by checking that the index j is not null anymore.

3 Comments

I'm sorry but I can't read this code. What I like about this though is the fact that it has early stopping.
@Philipp I don't get what you mean with "can't read this code". As in I don't understand how it works or what?
I don't understand how it works. I understand that you are implementing the idea of a loop where I would save the first string and then compare to it in the later iterations. However I - for instance - don't understand what is the point of the j != null. In my head this is not necessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.