This is the sixth day of my participation in the More text Challenge. For more details, see more text Challenge
In the last article, we summarized the basic common APIS for arrays. This article continues with a look at some of the common utility methods for arrays
Array to string
- Join (): join all the elements of an array (or an array-like object) into a string and return the string. If the array has only one item, the item is returned without a delimiter.
- ToString (): Returns a string representing the object
- Reduce (): Execute a reducer (ascending) function that you provide for each element in the array, summarizing the results into a single return value.
const arr = ["a"."b"."c"."d"."e"."f"];
/ / way
const str = arr.join(",");
2 / / way
const str1 = arr.toString();
3 / / way
const str2 = arr.reduce(function (accumulator, currentValue) {
return accumulator + "," + currentValue;
}, "");
Copy the code
String to array
- Split (): Splits a String into an array of substrings using the specified delimiter String, with a specified split String to determine the location of each split.
const str = "a,b,c,d,e,f ";
const arr = str.split(",");
Copy the code
Sort an array
- reverse()
- sort()
Sort (), reverse() defaults to calling String() on each item and then comparing the order of the strings – comparing their sequence of UTF-16 code unit values (in the Unicode character set).
If you want to sort in the specified way, you need to pass a sort function
We practice
Here is an example of using sort() directly to sort numbers in an array
const arr = [0.19.5.80.15, -1, -100];
arr.sort();
const strArr = [...arr].map((item) = > {
// Get the Unicode code for the string
const unicodeNum = `${item}`.codePointAt();
return {
// The number itself
num: item,
/ / Unicode code
unicodeNum,
};
});
console.log("str", strArr);
// Print the result of the sort
console.log("arr", arr);
Copy the code
Sort () affects the original array, but we can’t affect the original data after sorting, so we need to generate a new array
We can see that the result of arr.sort() is the same as that of strArr unicodeNum
Come on! Analyze a wave of causes
-
Before sorting, JS internally converts each element to a String via String(), returning a decimal representation of the String;
-
Convert each element to Unicode code via item.codePointat (a);
-
String. The prototype. CodePointAt: (a) returns a Unicode code point value.
-
The argument a is the position of the element in the string to be transcoded (it is an integer greater than or equal to zero and less than the length of the string). If it is not a value, it defaults to 0)
-
-
Ascending arrangement;
Below is a representation of Unicode code points for characters, so that we can verify the accuracy of string sorting!
- “-” the Unicode corresponding to the minus sign is
45
- The Unicode equivalent of “1” is
49
.
Earlier we also explained how to obtain Unicode in JS code, i.e
"1".codePointAt();
/ / 45
Copy the code
-
CodePointAt does not pass an argument, so the argument defaults to 0, so take the 0th position of the string “-1”, which is the “-” minus sign
-
“-” the minus sign is transcoded: “-“.codepointat () results in 45
Based on the above analysis, it is concluded that:
[0, 19, 5, 80, 15, -1, -100].sort(
["0", "1","5", "8", "1" , "-", "-"].sort()
To test our results, here we go! Practice is the sole criterion for testing truth! Sample code to go!
const arr2 = [
{ num: 0.tag: "0" },
{ num: 19.tag: "1" },
{ num: 5.tag: "5" },
{ num: 80.tag: "8" },
{ num: 15.tag: "1" },
{ num: -1.tag: "-" },
{ num: -100.tag: "-"},];// Take the first character of the array -arr and sort it in Unicode
arr2.sort((a, b) = > a.tag.codePointAt() - b.tag.codePointAt());
const strArr2 = [...arr2].map((item) = > {
const unicodeNum = `${item.tag}`.codePointAt();
return {
num: item.num,
unicodeNum,
};
});
console.log("-- -- -- -- -- -- -- -- -- -- -- -- -- -");
console.log("strArr2", strArr2);
console.log("arr2", arr2);
Copy the code
And the first demo results can be said to be exactly the same!!
Digital sorting
const arr = [0.19.5.80.15, -1, -100];
/ / ascending
const datas1 = [...arr].sort((a, b) = > a - b);
/ / descending
const datas1 = [...arr].sort((a, b) = > b - a);
Copy the code
Sort an attribute of type Number in an array
const list = [
{ age: 100.name: "wang" },
{ age: 12.name: "wang1" },
{ age: 1.name: "wang2" },
{ age: 89.name: "wang3" },
{ age: 2.name: "wang4"},];/* * @param {String} keyword attribute * @param {String} keyword type sortType (descending 'desc', ascending 'asce') */
const sortArrayObj = (keyword, sortType = "asce") = > {
// The default order is ascending
if (sortType === "asce") {
return (item1, item2) = > item1[keyword] - item2[keyword];
}
if (sortType === "desc") {
return (item1, item2) = > item2[keyword] - item1[keyword];
}
return 0;
};
const newDatas1 = [...list].sort(sortArrayObj("age"));
console.log(newDatas1);
Copy the code
Sort () affects the original array, but we can’t affect the original data after sorting, so we need to generate a new array
The sorting in English
- LocaleCompare (): Returns a number indicating whether a reference string is before or after the sort order or the same as the given string.
const datas = ["e"."d"."g"."c"."b"."a"];
const list = [
{ age: 100.name: "e" },
{ age: 12.name: "d" },
{ age: 1.name: "c" },
{ age: 89.name: "b" },
{ age: 2.name: "a"},];const res = [...list].sort((a, b) = > `${a.name}`.localeCompare(`${b.name}`));
/* 0: {age: 2, name: "a"} 1: {age: 89, name: "b"} 2: {age: 1, name: "c"} 3: {age: 12, name: "d"} 4: {age: 100, name: "e"} */
console.log(res);
Copy the code
When comparing a large number of strings, such as arrays, it is a good idea to create an intl.collator object and use the function provided by the compare (en-us) property.
const datas = ["e"."d"."g"."c"."b"."a"];
const res = [...datas].sort(new Intl.Collator("en").compare);
// ["a", "b", "c", "d", "e", "g"]
console.log(res);
Copy the code
Chinese sorting
What if we want our Chinese to be sorted in alphabetical order?
In this case, you can use the BCF 47 language tag string zh in simplified Chinese. The code is as follows:
var arrUsername = [
"Chen"."Deng chao"."Du Chun"."Feng Shaofeng"."Han geng"."Brief"."Huang Xiaoming"."Jia Nailang"."李晨"."Li Yifeng"."Lu Han"."Jing Boran"."Liu ye"."陆毅"."Sun Honglei",]; arrUsername.sort(new Intl.Collator("zh").compare);
/ / the result is: [" Chen ", "deng chao," "Du Chun", "through time and space", "han geng", "brief", "huang xiaoming," "smile", "jingboran", "15", "li yi feng", "liu ye", "lu", "Lu Han", "sun hong2 lei2"]
Copy the code
Intl API details can refer to this article JS Intl object complete introduction and application in Chinese
For maximum
- Math.max(): Returns the maximum number in a set.
console.log(Math.max(1.3.2));
// expected output: 3
console.log(Math.max(-1, -3, -2));
// expected output: -1
const array1 = [1.3.2];
console.log(Math.max(... array1));// expected output: 3
Copy the code
- Reduce (): Performs a function (ascending) that you provide for each element in the array, summarizing the results into a single return value.
const list = [{ x: 22 }, { x: 42 }, { x: 42 }];
const data = list.reduce(
(acc, cur) = > {
return Math.max(acc.x || acc, cur.x || cur);
},
{ x: -Infinity});// Filter the corresponding data by value
const res = list.filter((item) = > item.x === data);
/* 0: {x: 42} 1: {x: 42} */
console.log(res);
Copy the code
Add, subtract, multiply and divide numbers
Use reduce()
const list = [1.2.3.4.5.6.7.8.9];
/* * @param {Array} arr Array (each element must be a number) * @param {String} type Evaluate type * Add 'add', subtract 'subtraction' * multiply 'multi ', divide 'division' */
function calculator(arr, type) {
if (!Array.isArray(arr)) {
throw new Error("Please pass in an array.");
}
const obj = {
add: (a, b) = > a + b,
subtraction: (a, b) = > a - b,
multiplication: (a, b) = > a * b,
division: (a, b) = > a / b,
};
if(! obj[type]) {
throw new Error("Please enter the correct operator.");
}
const res = arr.reduce((count, current, index, source) = > {
return obj[type](count, current);
});
return res;
}
const data = calculator(list, "add");
/ / 45
console.log(data);
Copy the code
Count the number of occurrences of each element in the array
Use reduce()
const names = ["Alice"."Bob"."Tiff"."Bruce"."Alice"];
const countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
} else {
allNames[name] = 1;
}
return allNames;
}, {});
console.log(countedNames);
Copy the code
Convert a two-dimensional array to a one-dimensional array
Use reduce()
var flattened = [
[0.1],
[2.3],
[4.5],
].reduce(function (a, b) {
returna.concat(b); } []);console.log("Turn a two-dimensional array into a one-dimensional array.");
console.log(flattened);
Copy the code
Use a recursive implementation
// Hand-written implementation
/* Each element in an array is like a child node. Non-array elements are leaf nodes. Therefore, the input array in this example is a tree of height 2 with seven leaves. Flattening this array is essentially a sequential walk through the leaves. First argument: source array second argument: specifies the level of leveling to nest third argument: new array */
function flatten(sourceArray, depth, flattenedArray = []) {
for (const element of sourceArray) {
if (Array.isArray(element) && depth > 0) {
flatten(element, depth - 1, flattenedArray);
} else{ flattenedArray.push(element); }}return flattenedArray;
}
const arr = [[0].1.2[3[4.5]], 6];
console.log(flatten(arr, 1));
// [0, 1, 2, 3, [4, 5], 6]
Copy the code
Use the flat() implementation
Array.prototype.flat() is used to “flaten” a nested Array into a one-dimensional Array. This method returns a new array with no effect on the original data.
const arr1 = [0.1.2[3.4]].console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const arr2 = [0.1.2[[[3.4]]]];
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]
Copy the code
Refer to ES Introduction – Flat for details
Flattens deeply nested objects in an array into one dimension
const treeData = [
{
title: "0".value: "0".children: [{title: "0-0".value: "0-0".parentId: "0".children: [{title: "0-0-1".value: "0-0-1".parentId: "0-0",},],}, {title: "0-1".value: "0-1".parentId: "0".children: [{title: "0-1-1".value: "0-1-1".parentId: "0-1".children: [{title: "0-1-1-1".value: "0-1-1-1".parentId: "0-1-1",},],},],},],},];// Convert the tree data into a one-dimensional array
const flatData = (datas, res = []) = > {
if (Array.isArray(datas) && datas.length > 0) {
datas.forEach((item) = > {
const{ children, ... rest } = item; res.push(rest); flatData(children, res); }); }return res;
};
const res = flatData(treeData, []);
console.log(res);
Copy the code
Convert a particular one-dimensional array structure into tree data
const list = [
{ title: "0".value: "0" },
{ title: "0-0".value: "0-0".parentId: "0" },
{ title: "0-0-1".value: "0-0-1".parentId: "0-0" },
{ title: "0-1".value: "0-1".parentId: "0" },
{ title: "0-1-1".value: "0-1-1".parentId: "0-1" },
{ title: "0-1-1-1".value: "0-1-1-1".parentId: "0-1-1"},];// Convert a specific one-dimensional array structure to tree data
const arrToTreeData = (datas, root = []) = > {
const generatorData = (allDatas, childDatas) = > {
const newparentDatas = childDatas.map((childItem) = > {
// Child node data
const nextChildDatas = allDatas.filter(
(aallItem) = > aallItem.parentId === childItem.value,
);
if (Array.isArray(nextChildDatas) && nextChildDatas.length > 0) {
// Set the children of the parent node
childItem.children = nextChildDatas;
generatorData(allDatas, nextChildDatas);
}
return childItem;
});
return newparentDatas;
};
if (Array.isArray(datas) && datas.length > 0) {
// Data without a parent node is the root node
root = datas.filter((item) = >! item.parentId); root[0].children = [];
// Find the data whose parent is the root node
const childDatas = list.filter((item) = > item.parentId === root[0].value);
if (Array.isArray(childDatas) && childDatas.length > 0) {
const newChild = generatorData(list, childDatas);
// Set children for the root node
root[0].children = newChild; }}return root;
};
const res = arrToTreeData(list, []);
// Print out the treeData
console.log(res);
Copy the code
Array intersection
const a = [0.1.2.3.4.5];
const b = [3.4.5.6.7.8];
const duplicatedValues = [...new Set(a)].filter((item) = > b.includes(item));
duplicatedValues; / / [3, 4, 5]
Copy the code
Array difference set (merge and de-duplicate arrays)
const a = [0.1.2.3.4.5];
const b = [3.4.5.6.7.8];
const diffValues = [...new Set([...a, ...b])].filter(
(item) = >! b.includes(item) || ! a.includes(item), );// [0, 1, 2, 6, 7, 8]
Copy the code
Check whether all elements of the array meet the criteria
const arr = [1.2.3.4.5];
const isAllNum = arr.every((item) = > typeof item === "number");
Copy the code
Check whether any element in the array meets the criteria
const arr = [1.2.3.4.5]
const hasNum = arr.some(item => typeof item === 'number')
Copy the code
Find the maximum and minimum values of the array
const arr = [1.2.3];
MathMax (... arr);/ / 3
MathMin (... arr);/ / 1
Copy the code
Counts the number of identical items in an array
A lot of times, you want to count the number of recurring items in an array and represent them in an object. Then you can use the reduce method to process the array.
The following code counts the number of cars of each type and represents the total as an object.
var cars = ["BMW"."Benz"."Benz"."Tesla"."BMW"."Toyota"];
var carsObj = cars.reduce(function (obj, name) {
obj[name] = obj[name] ? ++obj[name] : 1;
return obj;
}, {});
carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }
Copy the code
Here’s another example
Suppose you have a sequence and you want to update each of its entries (map functionality) and then filter some of them (Filter functionality). If you use map first and then filter, you need to iterate through the array twice.
In the code below, we double the values in the sequence and then pick out those numbers greater than 50. Notice how we use Reduce very efficiently to accomplish both map and Filter methods?
const numbers = [10.20.30.40];
const doubledOver50 = numbers.reduce((finalList, num) = > {
num = num * 2;
if (num > 50) {
finalList.push(num);
}
returnfinalList; } []); doubledOver50;/ / [60, 80]
Copy the code
Use deconstruction to exchange parameter values
let param1 = 1;
let param2 = 2;
[param1, param2] = [param2, param1];
console.log(param1); / / 2
console.log(param2); / / 1
Copy the code
Use Reduce to check whether the parentheses match
Another use of Reduce is the ability to match parentheses in a given string. For a string with parentheses, we need to know whether the amount of (and) is the same and whether (appears before).
In the code below we can easily solve this problem using Reduce. All we need to do is declare a counter variable, which starts at 0. Incrementing counter by one when encountered, subtracting counter by one when encountered. If the number of left and right brackets matches, the final result is 0.
//Returns 0 if balanced.
const isParensBalanced = (str) = > {
return str.split("").reduce((counter, char) = > {
if (counter < 0) {
//matched ")" before "("
return counter;
} else if (char === "(") {
return ++counter;
} else if (char === ")") {
return --counter;
} else {
//matched some other char
returncounter; }},0); //<-- starting value of the counter
};
isParensBalanced("(())"); // 0 <-- balanced
isParensBalanced("(asdfds)"); //0 <-- balanced
isParensBalanced("()"); // 1 <-- not balanced
isParensBalanced(") ("); // -1 <-- not balanced
Copy the code
Implement stacks and queues
Stack: a more appropriate example is the code brick, folding plate, etc., put on the top of the first use, put on the following use, that is, after the first out
Queuing: A good example is queuing to buy something. The person at the front of the queue gets it first
A rough implementation of the stack
const stack = [];
/ / into the stack
stack.push("a");
/ / out of the stack
stack.pop();
Copy the code
Rough implementation of queues
const quen = [];
/ / team
quen.push("a");
/ / out of the team
stack.unshfit();
Copy the code
Sorting algorithm -todo
For more information about several sorting algorithms, please refer to this article 🍕 array sorting algorithms of JavaScript knowledge system
Depth copy array -todo
Refer to this article for depth and depth copies of JavaScript
Array deduplicate -todo
Refer to the JavaScript body of Knowledge for array reweighting
Related algorithm to think about the question
- Merge two ordered arrays – double pointer method
- Find the sum of two numbers in an array to be equal to 9- object mapping
- Find the sum of three numbers in an array equal to 0- collision pointer method
- …
- Please use the array [4-trichlorobenzene [1], [1, 2, 3], [4] 1, 31 [1]] quick sort into [[1, 2, 3], [1, 4-trichlorobenzene], 31 [1], [1 4]], how to solve
The last
The above is the main content of this article, the article is shallow, welcome you to see the comment area to leave your opinion!
Feel the harvest of students welcome to like, follow a wave!
The articles
- Front end developers should know Centos/Docker/Nginx/Node/Jenkins (🍡 long)
- Qr code scan code login is what principle
- The most complete ECMAScript guide
- Package. json that front-end developers need to know