用每x个单词的组合将字符串分解为数组

时间:2019-01-31 20:33:48

标签: javascript

我的JavaScript字符串很长。我试图将它与连续单词的每个x组合分解成一个数组。例如,如果我的数组

var string = 'This is my example string'

我的x等于3,我会得到类似的东西:

['This', 'This is', 'This is my', 'is', 'is my', 'is my example', 'my', 'my example', 'my example string', 'example string', 'string']

就像,每个组合最多三个单词。我以此为指标进行模糊文本匹配。

3 个答案:

答案 0 :(得分:3)

您可以使用双for循环:

function chunks(str, len) {
    const arr = str.match(/\S+/g);
    const result = [];
    for (let i = 0; i < arr.length; i++) {
        const end = Math.min(arr.length, i + len);
        for (let j = i + 1; j <= end; j++) {
            result.push(arr.slice(i, j).join(" "));
        }
    }
    return result;
}


var string = 'This is my example string';
console.log(chunks(string, 3));

更实用的方法是:

function chunks(str, len) {
    return str.match(/\S+/g).flatMap((_, i, arr) => 
        arr.slice(i, i + len).map((_, j) => arr.slice(i, i+j+1).join(" "))
    );
}

var string = 'This is my example string';
console.log(chunks(string, 3));

答案 1 :(得分:2)

您可以缩小数组,并使用Set来获取不确定值。

var string = 'This is my example string',
    result = [... new Set(string.split(' ').reduce((r, s, i, a) =>
        r.concat(
            s,
            a.slice(i, i + 2).join(' '),
            a.slice(i, i + 3).join(' ')
        ),
        []
    ))];

console.log(result);

答案 2 :(得分:1)

一种纯功能性方法:

// permuteWords :: Number -> String -> [String]
const permuteWords = count => x => {
    const words = x.split (' ')
    const wordIndexes = [...words.keys ()]

    return wordIndexes.flatMap (i => {
        const wordIndexes_ = wordIndexes.slice (i, count + i)

        return wordIndexes_.map (i_ => 
            words.slice (i, i_ + 1).join (' ')
        )
    })
}

const output = permuteWords (3) ('This is my example string')

console.log (output)

第二点:更多细分使事情变得更简单!

现在,我已经定义permuteBy来生成表示排列的索引的平面数组,然后使用它们顺序获取每个单词:

// rangeFromZero :: Number -> [Number]
const rangeFromZero = x => [...Array (x).keys ()]

// permuteBy :: Number -> Number -> [Number]
const permuteBy = x => y => {
    const ys = rangeFromZero (y)

    return ys.flatMap(i => 
        ys.slice (i, x + i).flatMap (i_ => ys.slice(i, i_ + 1))
    )
}

// permuteWords :: Number -> String -> [String]
const permuteWords = count => x => {
    const words = x.split (' ')
    
    return permuteBy (count) (words.length)
                  .map (i => words[i])
}

const output = permuteWords (3) ('This is my example string')

console.log (output)