以下函数将文件(queries)中的字符串与其他两个文件(archives)的字符串进行匹配。我包括了重要的日志:

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/

10-11 23:38