“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”
Learn 10 practical Javascript code snippets every day, deepen your understanding of Javascript syntax, accumulate code optimization experience, today is the second part, of course, you can continue to check the finished code snippets “Learning 10 Practical Javascript Snippets every day (I)”.
1. forObject
This code snippet iterates through each property of the object and iterates one callback for each property.
const forObject = (obj, callback) => Object.keys(obj).forEach((key) => callback(obj[key], key, obj)); Const testObj = {title: "# ", author:" # ",}; forObject(testObj, (val, key) => { console.log(`${key}:${val}`); }); // title: learn 10 useful Javascript snippet (1) // authorCopy the code
2. forReverse
This code snippet iterates through the array in reverse order, starting with the last element of the array and going forward through each element of the array and performing a callback function.
const forReverse = (array, callback) =>
array.slice(0).reverse().forEach(callback);
const testArray = [1, 2, 3, 4];
forReverse(testArray, (val) => console.log(val));
// 4
// 3
// 2
// 1
Copy the code
The reduceRight() method accepts a function as an accumulator and reduces each value of the array (from right to left) to a single value, thanks to a friendly tip from digger. However, the current support level is not widespread, and the environment needs to be considered when using
const testArray = [1.2.3.4];
const forReduce = (array, callback) = > {
array.reduceRight((acc, current) = > callback(current), 0);
};
forReduce(testArray, (val) = > console.log(val));
Copy the code
3. flatten
This code snippet uses recursion to flatten a group of numbers to a specified depth. There are functions available in ES6 to do this. Here are 7 JavaScript Coding Tips you should Know.
const flatten = (array, depth = 1) => array.reduce( (acc, current) => acc.concat( depth > 1 && Array.isArray(current) ? flatten(current, depth - 1) : current ), [] ); const arrayTest = [0, 1, 2, [[[3, 4, [5]]]]]; console.log(flatten(arrayTest)); // [ 0, 1, 2, [ [ 3, 4, [Array] ] ] ] console.log(arrayTest.flat()); // [ 0, 1, 2, [ [ 3, 4, [Array] ] ] ] const depth = 3; console.log(flatten(arrayTest, depth)); // [ 0, 1, 2, 3, 4, [ 5 ] ] console.log(arrayTest.flat(depth)); // [0, 1, 2, 3, 4, [5]]Copy the code
4. deepFlatten
This code fragment uses recursion to flatten the array completely. In contrast to the above function, this function flattens the array completely without specifying the depth.
const deepFlatten = (array) => [].concat( ... array.map((item) => (Array.isArray(item) ? deepFlatten(item) : item)) ); const arrayTest = [0, 1, 2, [[[3, 4, [5]]]]]; console.log(deepFlatten(arrayTest)); // [0, 1, 2, 3, 4, 5]Copy the code
5. findKey
This code snippet finds an object by key value and returns the first key that satisfies a given function.
const findKey = (obj, fn) =>
Object.keys(obj).find((key) => fn(obj[key], key, obj));
const testObj = {
hballard: { age: 36 },
sguzman: { age: 40 },
plowe: { age: 32 },
};
console.log(findKey(testObj, (item) => item.age > 32)); // hballard
Copy the code
6. filterDuplicate
This code snippet filters duplicates in an array, which is a classic use case for Set. For more information on the use of sets, see Set Data Manipulation in JavaScript: Intersection, Difference Set, Intersection, and Symmetric Difference Set.
const filterDuplicate = (arr) => [...new Set(arr)];
const testArray = [1, 3, 4, 5, 5, 5, 6, 2, 9];
console.log(filterDuplicate(testArray)); // [1, 3, 4, 5, 6, 2, 9]
Copy the code
7. dropWhile
This snippet removes elements from the array until the passed function returns true. That is, the first element of the array is deleted, and the function stops when the deleted element returns true.
const dropWhile = (array, fn) => { while (array.length > 0 && ! fn(array[0])) array = array.slice(1); return array; }; const testArray = [30, 29, 33, 31, 28]; console.log(dropWhile(testArray, (item) => item >= 33)); // [33, 31, 28]Copy the code
8. digitize
This code snippet splits a number into an array of individual numbers. This is the extension operator… The more classical method of use. For more information on the use of extension operators, see 8 Ways to Use extension Operators in ES6.
const digitize = (number) => [...`${number}`].map((item) => parseInt(item)); console.log(digitize(2021)); // [2, 0, 2, 1]Copy the code
9 .differenceWith
This code snippet removes the value that the comparator function returns as false, which can also be used to find the difference set between two arrays.
const differenceWith = (array1, array2, comp) => array1.filter((a) => array2.findIndex((b) => comp(a, b)) === -1); const a1 = [1, 2, 3, 4]; const a2 = [3, 4, 5, 6]; console.log(differenceWith(a1, a2, (a, b) => a === b)); // [1, 2]Copy the code
10. defer
This code snippet delays the execution of the function until the current call stack is complete.
const defer = (fn, ... args) => setTimeout(fn, 1, ... args); defer(console.log, "devpoint"); console.log("juejin"); // First juejin, then DevpointCopy the code