如何比较两个数组并找到元素不同的索引?



在Scala中是否有任何内置函数(比较后无法获取索引)?

下面是一些我已经有了的JavaScript代码:

var diffIndexes = [];
var newTags = ['a','b','c'];
var oldTags = ['c'];
var diffValues = arrayDiff(newTags, oldTags);
console.log(diffIndexes); // [0, 1]
console.log(diffValues); // ['a', 'b'] "

使用zipWithIndexunzip可以很容易做到

val (diffValues, diffIndexes) = newTags.zipWithIndex.filter(c => !oldTags.contains(c._1)).unzip

在Scastie运行的代码

您可以这样做:

def arrayDiff[T](newTags: List[T], oldTags: List[T]) = {
oldTags.foldLeft(newTags.zipWithIndex.toMap) {
case (seed, char) => {
seed.get(char) match {
case Some(_) => seed - char
case _ => seed
}
}
}
}

val newTags = List('a', 'b', 'c')
val oldTags = List('c')
val (diffIndexes, diffValues) = arrayDiff(newTags, oldTags).unzip
println(diffIndexes) // List(a, b)
println(diffValues) // List(0, 1)

我不确定这是否是你的意思,因为当oldTags有一些newTags没有的值时,你想做什么?在我的情况下,它将忽略oldTag,因为它不在newTags

中。

最新更新