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.

Philipp
  • 1,191
  • 1
  • 14
  • 16

2 Answers2

3

You could do something like

set = new Set(yourArray)
set.delete(null)
if (set.size === 1)
   // unique
gog
  • 10,367
  • 2
  • 24
  • 38
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.
Thomas
  • 11,958
  • 1
  • 14
  • 23
  • 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 Jun 19 '23 at 13:25
  • @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? – Thomas Jun 19 '23 at 13:31
  • 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. – Philipp Jun 19 '23 at 14:36