我有一个数组数组
const arr = [
['foo', 'bar', 'hey', 'oi'],
['foo', 'bar', 'hey'],
['foo', 'bar', 'anything'],
['bar', 'anything']
]
我试图获取出现在所有数组中的字符串,在这种情况下,它们仅是bar
。
我用.filter
尝试了很多事情,但是一切看上去都很混乱。
有没有简单的解决方案来找到出现在所有数组中的字符串?
我尝试过的
const arr = [
['foo', 'bar', 'hey', 'oi'],
['foo', 'bar', 'hey'],
['foo', 'bar', 'anything'],
['bar', 'anything']
]
const keySet = new Set()
arr.forEach(x => x.forEach(y => keySet.add(y)))
const uniqueKeys = Array.from(keySet)
console.log(uniqueKeys)
const res = uniqueKeys.filter(x => !arr.some(y => !y.includes(x)))
console.log(res)
答案 0 :(得分:4)
您可以分两个步骤进行操作:
filter()
。(可以使用一个元素)filter()
内使用every()
或原始数组,并检查该元素是否存在于所有数组中。
const arr = [
['foo', 'bar', 'hey', 'oi'],
['foo', 'bar', 'hey'],
['foo', 'bar', 'anything'],
['bar', 'anything']
]
const res = arr[0].filter(x => arr.every(a => a.includes(x)));
console.log(res)
答案 1 :(得分:1)
您可以通过使用Set
进行过滤来缩小数组。
const
array = [['foo', 'bar', 'hey', 'oi'], ['foo', 'bar', 'hey'], ['foo', 'bar', 'anything'], ['bar', 'anything']],
common = array.reduce((a, b) => a.filter(Set.prototype.has, new Set(b)));
console.log(common);
答案 2 :(得分:0)
您可以结合使用reduce
和filter
来获取所有数组之间的交集:
const res = arr.reduce((acc, a) => acc.filter(value => a.includes(value) ), arr[0])
如果使用lodash
,则代码会更简单:
const _ = require('lodash');
const res = _.intersection(...arr);
答案 3 :(得分:0)
使用package br.com.generaldq.utils
import org.apache.log4j.Logger
object HiveUtils {
val log: Logger = Logger.getLogger(HiveUtils.getClass)
def beelineExec(hql: String, queue: String = "DataQuality"): String = {
// here the beeline call and parameters are fixed,
// no reuse of Spark configurations.
val serversHive=List("etc:2181", "etc2:2181")
log.info(hql)
val bl =
Seq("beeline", "-u", "'jdbc:hive2://etcEtc","--hiveconf","... ETC...", "-e",
"\""+hql+"\""
)
import sys.process._
var result =
try {
Process(bl).!!
} catch {
case e: Exception =>
log.error(s"Error '${e}' on executing Hive query.\nQuery: ${hql}\n")
s"Error on executing Hive query. Query: ${hql}"
}
result
}
}
,.filter()
和.flat()
。
.every()
答案 4 :(得分:0)
这是我可以提出的第一个解决方案,看看是否适合您
const arr = [
['foo', 'bar', 'hey', 'oi'],
['foo', 'bar', 'hey'],
['foo', 'bar', 'anything'],
['bar', 'anything']
];
const result = [];
arr[0].forEach(str => {
let present = true;
arr.slice(1).forEach(array => {
if (!array.includes(str))
present = false;
});
if (present)
result.push(str);
});
答案 5 :(得分:-4)
使用.filter就像:
const arr = [
str: {'foo', 'bar',
'hey', 'oi'},
str: {'foo', 'bar',
'hey'},
str: {'foo', 'bar',
'anything'},
str: {'bar',
'anything'}
]
const result = arr.filter((arr) => arr.str === bar)
console.log(result)
//gives you bar lines