字符串中单词出现次数

问题描述

// 给出如下字符串,请输出字符串中每个单词出现的次数
const str = 'yesterday is sunday, today is sunday, tomorrow is Sunday. so everyday is sunday.';

1. 正则

/**
 * 方法一
 * \w 表示匹配包括下划线的任何单词字符
 * () 括号用于获取子匹配
 * +  表示匹配前面的子表达式一次或多次
 * 
 * 当 result[key] 不存在时
 * result[key] = undefined
 * result[key]++ = NaN
 * result[key]++ || value = value
 */
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

// (cbObj[key]++ || (cbObj[key] = 1), cbObj)  <等价于>  cbObj[key]++ || (cbObj[key] = 1); return cbObj;
const arr = str.replace(/\,|\.|\s\s/gi, '').split(' ');
const result = arr.reduce((cbObj, key) => (cbObj[key]++ || (cbObj[key] = 1), cbObj), {});

排序

// 数组可排序,对象不可排序
// sort: 从小到大(a - b), 从大到小(b - a)

// 方式一
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); // 有序数组