
在前端开发中,我们经常需要处理复杂的数据结构,例如一个包含多个对象的数组,每个对象又包含一个子数组。一个典型的场景是,我们有一个表示nfl球队的数组,每支球队对象中包含一个球员名字的数组。我们的目标是统计所有球队中每个球员名字出现的总次数,并将其存储在一个以名字为键、出现次数为值的对象中。
var nflTeams = [
{ name: 'Kansas City Chiefs', playersFirstNames: ['Shane', 'Chad', 'Michael', 'Ronald', 'Blake', 'Noah'], champions: true },
{ name: 'Philadelphia Eagles', playersFirstNames: ['Jalen', 'Kenneth', 'Boston', 'Trey', 'Jack', 'Andre', 'Jack', 'Lane', 'Jason', 'Nakobe'], champions: false },
{ name: 'Cincinnati Bengals', playersFirstNames: ['Brandon', 'Joe', 'Chris', 'Joe', 'Tyler', 'Trenton', 'Trent', 'Mitchell', 'Alex', 'Trey', 'Ted'], champions: false },
{ name: 'San Francisco 49ers', playersFirstNames: ['Jimmy', 'Josh', 'Kyle', 'Jordan', 'Brandon', 'Danny', 'George', 'Tyler', 'Charlie', 'Jake', 'Nick', 'Nick', 'Kevin'], champions: false },
];期望的结果是一个类似 {'Joe': 2, 'Jimmy': 1, 'Jalen': 1, ...} 的对象。初学者可能会尝试使用 _.map()、_.flatten() 和 _.reduce() 组合来实现,但在 _.reduce() 阶段常会遇到逻辑错误。
Underscore.js 提供了一个专门用于统计集合中元素出现频率的利器——_.countBy() 方法。它能够根据给定迭代器(或属性名)对集合中的元素进行分组计数,极大地简化了频率统计的逻辑。
为了将嵌套的球员名字数组扁平化成一个单一的球员名字列表,我们可以结合使用原生 JavaScript 的 Array.prototype.flatMap() 或 Underscore.js 的 _.map() 和 _.flatten()。
如果你的项目环境支持 ES2019 或更高版本,Array.prototype.flatMap() 是一个非常简洁的选择,它能够先对数组的每个元素执行映射操作,然后将所有结果扁平化成一个新数组。
// 引入 Underscore.js
// <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
const nflTeams = [
{ name: 'Kansas City Chiefs', playersFirstNames: ['Shane', 'Chad', 'Michael', 'Ronald', 'Blake', 'Noah'], champions: true },
{ name: 'Philadelphia Eagles', playersFirstNames: ['Jalen', 'Kenneth', 'Boston', 'Trey', 'Jack', 'Andre', 'Jack', 'Lane', 'Jason', 'Nakobe'], champions: false },
{ name: 'Cincinnati Bengals', playersFirstNames: ['Brandon', 'Joe', 'Chris', 'Joe', 'Tyler', 'Trenton', 'Trent', 'Mitchell', 'Alex', 'Trey', 'Ted'], champions: false },
{ name: 'San Francisco 49ers', playersFirstNames: ['Jimmy', 'Josh', 'Kyle', 'Jordan', 'Brandon', 'Danny', 'George', 'Tyler', 'Charlie', 'Jake', 'Nick', 'Nick', 'Kevin'], champions: false },
];
const playerFirstNameCounts = _.countBy(nflTeams.flatMap(team => team.playersFirstNames));
console.log(playerFirstNameCounts);
// 预期输出: { 'Shane': 1, 'Chad': 1, 'Michael': 1, 'Ronald': 1, 'Blake': 1, 'Noah': 1, 'Jalen': 1, 'Kenneth': 1, 'Boston': 1, 'Trey': 2, 'Jack': 2, 'Andre': 1, 'Lane': 1, 'Jason': 1, 'Nakobe': 1, 'Brandon': 2, 'Joe': 2, 'Chris': 1, 'Tyler': 2, 'Trenton': 1, 'Trent': 1, 'Mitchell': 1, 'Alex': 1, 'Ted': 1, 'Jimmy': 1, 'Josh': 1, 'Kyle': 1, 'Jordan': 1, 'Danny': 1, 'George': 1, 'Charlie': 1, 'Jake': 1, 'Nick': 2, 'Kevin': 1 }这种方法首先使用 flatMap() 将所有球队的球员名字列表合并成一个扁平的数组,然后 _.countBy() 直接对这个扁平数组进行计数。
如果你倾向于完全使用 Underscore.js 的方法,或者环境不支持 flatMap(),你可以通过 _.chain() 将 _.map()、_.flatten() 和 _.countBy() 串联起来。
// 引入 Underscore.js
// <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
const nflTeams = [
{ name: 'Kansas City Chiefs', playersFirstNames: ['Shane', 'Chad', 'Michael', 'Ronald', 'Blake', 'Noah'], champions: true },
{ name: 'Philadelphia Eagles', playersFirstNames: ['Jalen', 'Kenneth', 'Boston', 'Trey', 'Jack', 'Andre', 'Jack', 'Lane', 'Jason', 'Nakobe'], champions: false },
{ name: 'Cincinnati Bengals', playersFirstNames: ['Brandon', 'Joe', 'Chris', 'Joe', 'Tyler', 'Trenton', 'Trent', 'Mitchell', 'Alex', 'Trey', 'Ted'], champions: false },
{ name: 'San Francisco 49ers', playersFirstNames: ['Jimmy', 'Josh', 'Kyle', 'Jordan', 'Brandon', 'Danny', 'George', 'Tyler', 'Charlie', 'Jake', 'Nick', 'Nick', 'Kevin'], champions: false },
];
const playerFirstNameCountsChained = _.chain(nflTeams)
.map('playersFirstNames') // 提取所有球队的 playersFirstNames 数组
.flatten() // 将所有球员名字数组扁平化为一个单一数组
.countBy() // 对扁平化后的数组进行计数
.value(); // 获取链式操作的最终结果
console.log(playerFirstNameCountsChained);
// 预期输出与上例相同这个方法清晰地展示了如何利用 Underscore 的链式调用能力,先通过 map('playersFirstNames') 提取出所有球队的球员名字数组集合,然后 flatten() 将这些数组合并成一个扁平的列表,最后 countBy() 完成计数。
虽然 _.countBy() 是此场景下的最佳实践,但理解 _.reduce() 的正确用法对于处理更复杂的聚合逻辑至关重要。许多初学者在尝试使用 _.reduce() 进行计数时会遇到问题,主要是因为对 JavaScript 运算符和 _.reduce() 回调函数返回值的理解不足。
原始尝试中的 _.reduce() 代码如下:
// 错误示例
var firstNameOccurence = _.chain(nflTeams)
.map(function(team) { return team.playersFirstNames })
.flatten()
.reduce(function(newObject, firstName) {
console.log('we have a first name of a player', firstName);
// 这里的逻辑是错误的
return newObject[firstName] = 1 ? !newObject[firstName] : newObject[firstName] += 1;
}, {})
.value();这段代码的问题在于 newObject[firstName] = 1 ? !newObject[firstName] : newObject[firstName] += 1; 这一行。让我们逐一分析:
_.reduce() 的回调函数必须始终返回累加器(currObject),以便在下一次迭代中继续使用它。正确的计数逻辑应该是在累加器对象上安全地递增计数。
// 引入 Underscore.js
// <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
const nflTeams = [
{ name: 'Kansas City Chiefs', playersFirstNames: ['Shane', 'Chad', 'Michael', 'Ronald', 'Blake', 'Noah'], champions: true },
{ name: 'Philadelphia Eagles', playersFirstNames: ['Jalen', 'Kenneth', 'Boston', 'Trey', 'Jack', 'Andre', 'Jack', 'Lane', 'Jason', 'Nakobe'], champions: false },
{ name: 'Cincinnati Bengals', playersFirstNames: ['Brandon', 'Joe', 'Chris', 'Joe', 'Tyler', 'Trenton', 'Trent', 'Mitchell', 'Alex', 'Trey', 'Ted'], champions: false },
{ name: 'San Francisco 49ers', playersFirstNames: ['Jimmy', 'Josh', 'Kyle', 'Jordan', 'Brandon', 'Danny', 'George', 'Tyler', 'Charlie', 'Jake', 'Nick', 'Nick', 'Kevin'], champions: false },
];
const playerFirstNameCountsReduced = _.chain(nflTeams)
.map('playersFirstNames')
.flatten()
.reduce((currObject, firstName) => {
// 如果 firstName 已经存在,则在其当前值上加 1;否则,将其初始化为 1。
currObject[firstName] = (currObject[firstName] || 0) + 1;
return currObject; // 始终返回累加器对象
}, {}) // 初始累加器是一个空对象
.value();
console.log(playerFirstNameCountsReduced);
// 预期输出与上例相同在这个正确的实现中:
注意事项: 另一种更简洁的 reduce 回调写法是 ((currObject, firstName) => ({...currObject, [firstName]: (currObject[firstName] || 0) + 1}))。这种写法在每次迭代时都会创建一个新对象,并复制所有现有属性,然后添加或更新当前 firstName 的计数。虽然代码看起来更简洁,但从性能角度来看,它在每次迭代中都会创建新对象并遍历现有属性,因此效率不如直接修改 currObject 的方法。在处理大型数据集时,应优先考虑直接修改 currObject 的方式。
从嵌套数组中统计元素频率是一个常见的需求。Underscore.js 提供了强大的工具来简化这一过程:
选择合适的工具和正确实现逻辑是编写高效、可维护代码的关键。在处理数据聚合和转换时,优先考虑使用库提供的专用方法(如 _.countBy()),因为它们通常经过优化且意图明确。当需要更复杂的自定义聚合时,再深入利用 _.reduce(),并确保其逻辑的严谨性。
以上就是Underscore.js 链式调用:从嵌套数组中统计元素出现频率的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号