英文:
Check if all values in an array are equal but ignore null values
问题
我有一个字符串和空值的列表。现在我想检查列表中的所有字符串是否相同,应该忽略空值。例如:
- `[null, "a", "a", null, "a"]` 应该返回 `true`,因为所有字符串都相等
- `[null, "a", "a", null, "b"]` 应该返回 `false`,因为有 "b" 和 "a"
在SO上有其他与查找重复项或相等值有关的问题,但似乎没有一个考虑到`null`值。
我已经考虑过用以下方法实现:
- 一个循环,在第一个字符串被保存后,将在后续迭代中与其进行比较
- 一个`filter`后跟一个`every`
不过我想知道是否有更好、更直观的方法来做这件事。
英文:
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 totrue
, because all strings are equal[null, "a", "a", null, "b"]
should evaluate tofalse
, 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 byevery
However I was wondering if there is a better more intuitive way to do this.
答案1
得分: 3
你可以这样做:
set = new Set(yourArray)
set.delete(null)
if (set.size === 1)
// unique
英文:
You could do something like
set = new Set(yourArray)
set.delete(null)
if (set.size === 1)
// unique
答案2
得分: 1
- 一个循环,在其中我会保存第一个字符串,然后在后续迭代中与其进行比较。
- 一个筛选,然后是每个。
你可以通过一个空变量,然后接着使用 every
来实现它:
let j; // 第一个非空值
const result = array.every((v, i, a) => v === null || v === a[j ??= i]) && j != null;
编辑: 好的,让我们来分解这个代码:
every((v, i, a) => v === null || ...)
检查每个元素是null
或者...- 因此,只有在
v
不是null
时才执行v === a[j ??= i]
- j ??= i 基本上是
j === null || j === undefined ? (j = i) : j
的简写,所以j
将适应第一个v !== null
的i
- 但是我们的循环不区分
array.every((v, i, a) => v === null)
和array.every((v, i, a) => v === a[j ??= i])
,所以我们还想要检查v === a[j ??= i]
至少被执行了一次,通过检查索引j
不再为null
。
英文:
> - 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 eithernull
or ...- so
v === a[j??=i]
is only executed whenv
is notnull
- j ??= i is basically a shorthand for
j === null || j === undefined ? (j = i) : j
soj
will adapt the firsti
wherev !== null
- but our loop doesn't differentiate between
array.every((v,i,a) => v === null)
andarray.every((v,i,a) => v === a[j??=i])
so we also want to check thatv === a[j??=i]
was executed at least once by checking that the indexj
is not null anymore.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论