I am trying to count all combinations of matching strings in a textarea submit.
Eg:
USA Canada UK Australia Japan India
USA Canada India UK Australia China Brazil France
Brazil France Australia China
Expected results
2 consecutive words string match :
UK Australia = 2
USA Canada = 2
Brazil France = 2
Australia China = 2
1 consecutive words string match :
Canada UK = 1
Australia Japan = 1
Japan India = 1
India UK = 1
Australia China = 1
China Brazil = 1
France Australia = 1
I'm a beginner and just thinking about it gives me a headache.
Thank you for your time and it would be great if someone can help to write this function or point me to use any existing package, it would be much appreciated.
答案 0 :(得分:1)
您可以尝试
var string = ['USA Canada UK Australia Japan India', 'USA Canada India UK Australia China Brazil France', 'Brazil France Australia China']
string = string.join(' ')
var words = string.split(' ')
var wordGroups = {}
for( let i=1; i< words.length; i++ ){
let key = words[ i-1 ]+ '_' + words[ i ]
if( !wordGroups[ key ]) {
wordGroups[ key ] = 0
}
wordGroups[ key ] = wordGroups[ key ] + 1
}
Object.keys( wordGroups ).forEach( key =>{
let word = key.replace('_', ' ');
console.log( word , ': ', wordGroups[ key ])
})
答案 1 :(得分:0)
您可以用这种方式来做......
const arrayOfWords = "USA Canada UK Australia Japan India USA Canada India UK Australia China Brazil France Brazil France Australia China".split(" ");
const arrayOfPairs=[];
for(let i = 0;i<arrayOfWords.length-1;i++){
arrayOfPairs.push(arrayOfWords.slice(i,i+2).join(" "));
}
/* console.log(arrayOfPairs); */
const obj = arrayOfPairs.reduce((arr,ele,index)=>{
if(arr[ele]){
arr[ele] += 1;
return arr;
}
arr[ele]=1;
return arr;
},{})
console.log(obj);