alex alex - 11 days ago 8
Javascript Question

How to merge identical strings into a single array?

The following function matches the strings in a file (

queries
) with the strings of another two files (
archives
). I included the important logs:

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' ]


How to modify the code so I merge
matched
and end up with a result like this?

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


(Maybe I can use
.reduce
but I'm not very sure how.)

EDIT: I tried this:

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


But ended up with the same result.

Answer

This should do it:

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)

Store the results in an object, using the found string as a key.

For some cleaner data, you can just get the match counts, as fafl suggested:

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)