gpt4 book ai didi

javascript - 如何将相同的字符串合并到一个数组中?

转载 作者:行者123 更新时间:2023-11-28 18:15:00 25 4
gpt4 key购买 nike

以下函数将文件(查询)中的字符串与另外两个文件(存档)的字符串进行匹配。我包含了重要的日志:

console.log('q:', queries)
console.log('a:', archives)
queries.forEach(query => {
const regex = new RegExp(query.trim(), 'g')
archives.forEach(archive => {
const matched = archive.match(regex)
console.log('m:', matched)
})
})

q: [ 'one two', 'three four\n' ]
a: [ 'one two three four three four\n', 'one two three four\n' ]
m: [ 'one two' ]
m: [ 'one two' ]
m: [ 'three four', 'three four' ]
m: [ 'three four' ]

如何修改代码以便合并matched并最终得到这样的结果?

r1: [ 'one two',  'one two' ]
r2: [ 'three four', 'three four', 'three four' ]

(也许我可以使用.reduce,但我不太确定如何使用。)

编辑:我尝试过:

  const result = matched.reduce(function (a, b) {
return a.concat(b)
}, [])

但最终得到了相同的结果。

最佳答案

这应该可以做到:

var queries = [ 'one two', 'three four\n' ],
archives = [ 'one two three four three four\n', 'one two three four\n' ],
results = {};

queries.forEach(query => {
const regex = new RegExp(query.trim(), 'g')
archives.forEach(archive => {
const matched = archive.match(regex)
results[matched[0]] = (results[matched[0]] || []).concat(matched) || matched;
})
})

console.log(results)

使用找到的字符串作为键将结果存储在一个对象中。

对于一些更清晰的数据,您可以只获取匹配计数,如 fafl 建议的那样:

var queries = [ 'one two', 'three four\n' ],
archives = [ 'one two three four three four\n', 'one two three four\n' ],
results = {};

queries.forEach(query => {
const regex = new RegExp(query.trim(), 'g')
archives.forEach(archive => {
const matched = archive.match(regex)
results[matched[0]] = (results[matched[0]] || 0) + matched.length
})
})

console.log(results)

关于javascript - 如何将相同的字符串合并到一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40868866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com