preface
Count each character in a string such as STR = abcddcbaAABBC. The data result is represented as an object. Namely: {2, a: b: 2, c: 2, d: 2, a: 2, b: 2, c: 1}
Thinking way
1. First convert strings to arrays
Creates a new, shallow-copy Array instance from an array-like or iterable using the array.from () method, returning the new Array. Such as:
Array.from(str)
Copy the code
2.1 Create an empty object and judge characters by traversing the number group
Object.hasownproperty ();
The object.hasownProperty () method returns a Boolean value indicating whether the Object has the specified property in its own properties (that is, whether it has the specified key). const obj = {a:1}; obj.hasOwnProperty(“a”); Return true for example:
2.1 implementation
const str = "abcddcbaAABBC"
const arr = Array.from(str)
console.log(arr)
var obj = {}
for(i in arr){
if(obj.hasOwnProperty(arr[i])){
obj[arr[i]] = obj[arr[i]] + 1
}else{
obj[arr[i]] = 1}}console.log(obj)
Copy the code
{ a: 2.b: 2.c: 2.d: 2.A: 2.B: 2.C: 1 }
Copy the code
2.2 Use array.reduce () to count each element in an Array
The reduce() method performs a reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value.
Syntax: array.reduce (function(Total, currentValue, currentIndex, ARR), initialValue)
Example: [1, 2, 3, 4, 5]. The reduce ((calc, curr) = > [… calc, curr], []) output results as follows: [1, 2, 3, 4, 5] [… calc, curr] put curr the current element in calc array
[1,2,3,4,5]. Reduce ((calc,curr)=>calc+=curr,”) “12345” calc+=curr concatenates the current element of curr into calc
[1, 2, 3, 4, 5]. The reduce ((calc, curr) = > {return {[curr] : 1}}, {}) output is: {5} [curr] can get the current curr elements
For null, NaN, 0, and so on, the value of ~1 is -2, and the value of ~2 is -3, so the value of ~1 is -2.
2.2 implementation
var obj = arr.reduce((calc, curr) = > {
return {
...calc,
[curr]:-~calc[curr]
}
},{})
console.log(obj)
Copy the code
{ a: 2.b: 2.c: 2.d: 2.A: 2.B: 2.C: 1 }
Copy the code
conclusion
The string is converted to an Array by array.from ()
-
Use object.hasownProperty () to determine whether an empty Object contains elements from the array
-
The Array is accumulated by the accumulator array.reduce (). The result of the accumulation is presented in the form of an object. The key in the object is the element value of the Array. Finally, the cumulative calc object is returned.
If you return an object, be careful. If you return a custom object with a single expression, you will get an error without parentheses, because {… } there are syntax conflicts.