js中获取数组中的值出现的次数
In daily development, we often encounter the need to count the occurrences of each value in an array. Here are several methods to achieve this.
Method One
Approach
Use an object to store array values as keys, and check if they already exist in the object.
Steps
1. Create an empty object
2. Iterate through each element of the target array
3. Set the current element as the key in the object, and check if the value exists
4. If not, add the current element as a new key with a value of 1 (first occurrence)
5. If it already exists, increment the value by 1.
Code example:
let arr1 = [1,2,2,3,3,3,'a','b','b','c','c','c'];
function getArrItemNum(arr) {
let obj = {};
arr.forEach(element => {
if (obj[element]) {
obj[element]++;
} else {
obj[element] = 1;
}
});
return obj;
}
console.log(getArrItemNum(arr1)); // { '1': 1, '2': 2, '3': 3, a: 1, b: 2, c: 3 }
Notice: This method uses object keys for comparison, which may cause issues when dealing with character and numeric values (e.g., 'a' vs 1). For better compatibility, consider Method Two.
Method Two
Approach
Use ES6's Map type, which supports keys of any data type, to check for existing entries.
Steps
1. Create an empty Map
2. Iterate through each element of the target array
3. Set the current element as the key in the Map and retrieve its value
4. If the value exists, increment it and update the Map
5. If the value does not exist, add a new entry with value 1.
Code example:
let arr1 = [1,2,2,3,3,3,'a','b','b','c','c','c', '1', '1', '2'];
function getArrItemNum(arr) {
let mapObj = new Map();
arr.forEach(element => {
let num = mapObj.get(element);
if (num) {
mapObj.set(element, ++num);
} else {
mapObj.set(element, 1);
}
});
return mapObj;
}
console.log(getArrItemNum(arr1)); //
// Map(8) {
// 1 => 1,
// 2 => 2,
// 3 => 3,
// 'a' => 1,
// 'b' => 2,
// 'c' => 3,
// '1' => 2,
// '2' => 1
// }
Method Three
Approach
Use array object type combination, where each element represents a value and its count.
Steps
1. Create a new array
2. Sort the target array using the sort() method
3. Iterate through each element of the sorted array
4. Compare the current element with the previous one
5. If equal, increment the count of the last element in the new array
6. If not equal, add a new entry to the new array with the current element as the key and count 1.
Code example:
let arr1 = [1,2,2,3,3,3,'a','b','b','c','c','c', '1', '1', '2'];
function getArrItemNum(arr) {
let ArrObj = [];
arr.sort();
arr.forEach((element, index) => {
if (element === arr[index - 1]) {
ArrObj[ArrObj.length - 1].num++;
} else {
ArrObj.push({
key: element,
num: 1
});
}
});
return ArrObj;
}
console.log(getArrItemNum(arr1)); //
// [
// { key: 1, num: 1 },
// { key: '1', num: 2 },
// { key: 2, num: 2 },
// { key: '2', num: 1 },
// { key: 3, num: 3 },
// { key: 'a', num: 1 },
// { key: 'b', num: 2 },
// { key: 'c', num: 3 }
// ]
To sort by occurrence count, extend the code as follows:
let arr1 = [1,2,2,3,3,3,'a','b','b','c','c','c', '1', '1', '2'];
function getArrItemNum(arr) {
let ArrObj = [];
arr.sort();
arr.forEach((element, index) => {
if (element === arr[index - 1]) {
ArrObj[ArrObj.length - 1].num++;
} else {
ArrObj.push({
key: element,
num: 1
});
}
});
return ArrObj.sort((item1, item2) => item2.num - item1.num);
}
console.log(getArrItemNum(arr1)); //
// [
// { key: 3, num: 3 },
// { key: 'c', num: 3 },
// { key: '1', num: 2 },
// { key: 2, num: 2 },
// { key: 'b', num: 2 },
// { key: 1, num: 1 },
// { key: '2', num: 1 },
// { key: 'a', num: 1 }
// ]
---
**Key Improvements:**
1. Enhanced readability with clear section headings and bullet points
2. Standardized technical terms (e.g., "Map type", "sort() method")
3. Improved code formatting and structure
4. Added explanations for potential issues (e.g., character vs numeric values)
5. Maintained consistent terminology throughout the article