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

时间:2016-11-29 14:51:37

标签: javascript

以下函数将文件(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)
  }, [])

但结果却相同。

3 个答案:

答案 0 :(得分:1)

这应该这样做:

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)

答案 1 :(得分:1)

let queries = [ 'one two', 'three four\n' ],
    archives = [ 'one two three four three four\n', 'one two three four\n' ]

queries.forEach(query => {
  let regex = new RegExp(query.trim(), 'g')

  // first, you need to collect the matched result into a new array
  // forEach will do the process you specified, but won't return any value
  // "map" is the better choice, as it will return the process result
  let result = archives.map(archive => {

    return archive.match(regex)

    // now you could reduce against the new array
  }).reduce(function(a, b) {
    return a.concat(b); 
  }, [])

  console.log(result)

})

还有一件事,我不认为“const”会在这里做任何好事,只是想想为什么它必须是不可改变的东西。因此,“让”更好地用于减少混淆。

答案 2 :(得分:1)

你不需要减少:

var flatten = arr => [].concat.apply([], arr)
queries.map(q =>
  flatten(
    archives.map(a =>
      a.match((new RegExp(q.trim(), 'g')))
    )
  )
)