字符串中单词出现次数
问题描述
const str = 'yesterday is sunday, today is sunday, tomorrow is Sunday. so everyday is sunday.';
1. 正则
let result = {};
str.replace(/(\w)+/g, (key) => result[key]++ || (result[key] = 1));
2. map
let result = {};
const arr = str.replace(/\,|\.|\s\s/gi, '').split(' ');
arr.map(key => result[key]++ || (result[key] = 1));
3. reduce
const arr = str.replace(/\,|\.|\s\s/gi, '').split(' ');
const result = arr.reduce((cbObj, key) => (cbObj[key]++ || (cbObj[key] = 1), cbObj), {});
排序
const transformArr = Object.keys(result).map( key => ({[key]: result[key]}) );
transformArr.sort((a, b) => Object.values(b)[0] - Object.values(a)[0]);
const transformArr = Object.keys(result).map( key => ({word: key, len: result[key]}) );
transformArr.sort((a, b) => b.len - a.len);
输出
console.log(result);
console.log(transformArr);