迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中计算数组元素的出现次数

作者:迹忆客 最近更新:2023/03/10 浏览次数:

本教程将教你如何计算数组中元素的出现次数。我们将向你展示如何使用 Objects、Array.prototype.reduce、自定义函数和 Lodash 来实现。

你可以通过创建对象来计算元素数组的出现次数。之后,使用 for...of 循环将数组元素添加到对象中。

for...of 循环中,你检查元素是否已经在对象中;如果是这样,则将其值加一。否则,它是你添加到对象的新元素。

循环重复,直到将数组的所有元素及其频率添加到对象。这意味着对象中的属性是数组中的一个元素,它的值是它出现的次数。

因此,你可以使用 object[property] 检查元素是否出现,其中 property 是添加到 object 的数组元素。

结果将是它在数组中的出现。

const myArray = [3,2,3,3,5,6,5,5,8,4,4,7,7,7];
const counts = {};

for (const num of myArray) {
  counts[num] = counts[num] ? counts[num] + 1 : 1;
}

console.log(counts[2], counts[3], counts[4], counts[5], counts[6], counts[7], counts[8]);

输出:

1 3 2 3 1 3 1

Array.prototype.reduce 有两个参数:一个回调函数和一个初始值。将初始值设置为 Object 时,可以将该对象的属性设置为数组元素。

所以属性值将是元素的出现次数。为此,回调函数的第一次迭代将数组元素添加为对象的属性。

同时,它将它们的值设置为 1。

因此,后续迭代将检查属性值是否存在。如果为真,它将加一。

否则,它是一个新元素,将其值设置为 1。最后,该对象将包含元素数组及其值作为键值对。

let myArray = [2,2,3,5,6,2,1,1,1,4,5,6].reduce(function(accumulator, currentValue) {
  return accumulator[currentValue] ? ++accumulator[currentValue] : accumulator[currentValue] = 1, accumulator
},{});
console.log(myArray);

输出:

Object { 1: 3, 2: 3, 3: 1, 4: 1, 5: 2, 6: 2 }

你可以实现一个自定义函数,该函数将一个数组作为参数并返回两个数组。第一个将包含你作为参数传递给函数的数组的唯一元素。

而第二个将包含元素的出现次数。

这是计算数组元素出现次数的函数算法。

下面的代码是这个算法的实现。

let mArray = [2,3,4,1,2,2,5,3,7,8,1,1,6];

function countOccurrences(array) {
  let arrayElements 			= [],
      occurrences					= [],
      cloneOriginalArray 	= [...array],
      previousElement;

  // Sort the cloned array
  cloneOriginalArray.sort();
  for (let element of cloneOriginalArray) {
     if (element !== previousElement) { // That means it's a new element
       arrayElements.push(element); 	// push it into the array
       occurrences.push(1);					// push its occurence in the occurrence array
    } else ++occurrences[occurrences.length - 1]; // Not a new element, so increment its occurrence
      previousElement = element;
    }

  	return [arrayElements, occurrences];
}

const arrayAndItsOccurrences = countOccurrences(mArray);
console.log('[' + arrayAndItsOccurrences[0] + ']', '[' + arrayAndItsOccurrences[1] + ']');

输出:

[1,2,3,4,5,6,7,8] [3,3,2,1,1,1,1,1]

Lodash 有一个 .countBy 方法,它接受一个数组并返回一个对象。此对象包含数组中的元素及其作为键值对的值。

<body>
	<script
	src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"
	integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"
	referrerpolicy="no-referrer"
	>
	</script>
	<script>
		let loArray = [2,2,3,3,1,1,5,3,4,4,8,3,2,9];
		let lodash = _;
		let occurrences = _.countBy(loArray);
		console.log(occurrences)
	</script>
</body>

输出:

Object { 1: 2, 2: 3, 3: 4, 4: 2, 5: 1, 8: 1, 9: 1 }

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便