By Kapil Raghuwanshi

Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.

In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.

Use convenient and useful methods to reduce the number of lines of code, increase our productivity, and increase our fishing time.

In our daily tasks, we need to write functions such as sorting, searching, finding unique values, passing parameters, swapping values, etc., so here are a few common techniques and methods THAT I’ve cherished over the years to increase your time.

These tips will definitely help you:

  • Reduced lines of code
  • Coding Competitions
  • Increase your fishing time

1. Declare and initialize arrays

We can initialize the array with a specific size, or we can initialize the contents of the array by specifying a value. You might use an array, but you can also do this for a two-dimensional array, as follows:

const array = Array(5).fill(''); / / output (5) (" ", ""," ", ""," "] const matrix = Array (5). The fill (0). The map (() = > Array (5). The fill (0)) / / output (5) [Array (5), Array(5), Array(5), Array(5), Array(5)] 0: (5) [0, 0, 0, 0, 0] 1: (5) [0, 0, 0, 0, 0] 2: (5) [0, 0, 0, 0, 0] 3: (5) [0, 0, 0, 0, 0] 4: (5) [0, 0, 0, 0, 0] length: 5Copy the code

2. Summation, minimum and maximum

We should use the Reduce method to quickly find basic mathematical operations.

Const array =,4,7,8,9,2 [5];Copy the code

sum

array.reduce((a,b) => a+b); // Output: 35Copy the code

The maximum

array.reduce((a,b) => a>b? a:b); // Output: 9Copy the code

The minimum value

array.reduce((a,b) => a<b? a:b); // Output: 2Copy the code

3. Sort arrays of strings, numbers, or objects

We have built-in methods sort() and reverse() to sort strings, but what about numbers or arrays of objects

String array sort

const stringArr = ["Joe", "Kapil", "Steve", "Musk"] stringArr.sort(); / / output (4) [" Joe ", "Kapil", "Musk", "Steve"] stringArr. The reverse (); // Output (4) ["Steve", "Musk", "Kapil", "Joe"]Copy the code

Numeric array sort

const array = [40, 100, 1, 5, 25, 10]; array.sort((a,b) => a-b); / / output (6) [1, 5, 10, 25, 40, 100] array. The sort ((a, b) = > b - a); // Output (6) [100, 40, 25, 10, 5, 1]Copy the code

Object array sort

const objectArr = [ { first_name: 'Lazslo', last_name: 'Jamf' }, { first_name: 'Pig', last_name: 'Bodine' }, { first_name: 'Pirate', last_name: 'Prentice' } ]; objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name)); / / output (3) [{...}, {...}, {...}] 0: {first_name: "Pig", last_name: "Bodine"} 1: {first_name: "Lazslo", last_name: "Jamf"} 2: {first_name: "Pirate", last_name: "Prentice"} length: 3Copy the code

4. Filter virtual values from the array

False values like 0, undefined, null, false, “”, “” can be easily filtered out using the following techniques.

const array = [3, 0, 6, 7, '', false]; array.filter(Boolean); // Output (3) [3, 6, 7]Copy the code

5. Use logical operators to handle situations that require conditional judgment

function doSomething(arg1){ arg1 = arg1 || 10; // if arg1 has no value, take the default value 10} let foo = 10; foo === 10 && doSomething(); // if foo is equal to 10, just doSomething(); / / output: 10 foo = = = 5 | | doSomething (); // is the same thing as if (foo ! = 5) then doSomething(); // Output: 10Copy the code

6. Remove duplicate values

Const array =,4,7,8,9,2,7,5 [5]; array.filter((item,idx,arr) => arr.indexOf(item) === idx); // or const nonUnique = [...new Set(array)]; // Output: [5, 4, 7, 8, 9, 2]Copy the code

7. Create a counter object or Map

In most cases, you can create an object or Map to count the frequency of a particular word.

let string = 'kapilalipak'; const table={}; for(let char of string) { table[char]=table[char]+1 || 1; } {k: 2, a: 3, p: 2, I: 2, l: 2}Copy the code

or

const countMap = new Map(); for (let i = 0; i < string.length; i++) { if (countMap.has(string[i])) { countMap.set(string[i], countMap.get(string[i]) + 1); } else { countMap.set(string[i], 1); {}} / / output Map (5) "k" = > 2, "a" = > 3, "p" = > 2, "I" = > 2, "l" = > 2}Copy the code

8. Ternary operators are cool

function Fever(temp) { return temp > 97 ? 'Visit Doctor! ' : temp < 97 ? 'Go Out and Play!! ' : temp === 97 ? 'Take Some Rest! ': 'Go Out and Play! ';; } // Output Fever(97): "Take Some Rest!" Fever(100): "Visit Doctor!"Copy the code

9. Comparison of cyclic methods

  • The for and the for… In gets the index by default, but you can use arr[index].

  • for.. In also accepts non-numbers, so avoid using it.

  • forEach, for… Of directly gets the element.

  • ForEach can also get indexes, but for… Of not.

10. Merge two objects

const user = { name: 'Kapil Raghuwanshi', gender: 'Male' }; const college = { primary: 'Mani Primary School', secondary: 'Lass Secondary School' }; const skills = { programming: 'Extreme', swimming: 'Average', sleeping: 'Pro' }; const summary = {... user, ... college, ... skills}; Gender: "Male" name: "Kapil Raghuwanshi" Primary: "Mani Primary School" programming: "Extreme" secondary: "Lass Secondary School" sleeping: "Pro" swimming: "Average"Copy the code

11. Arrow function

Arrow function expressions are an alternative to traditional function expressions, but they are limited and cannot be used in all cases. Because they have lexical scope (parent scope) and do not have their own this and argument, they refer to the environment that defines them.

const person = { name: 'Kapil', sayName() { return this.name; } } person.sayName(); / / output Kapil ""Copy the code

But this:

const person = {
name: 'Kapil',
sayName : () => {
    return this.name;
    }
}
person.sayName();
// Output
"
Copy the code

13. Optional chains

const user = { employee: { name: "Kapil" } }; user.employee? .name; // Output: "Kapil" user.employ? .name; // Output: undefined user.employ. Name // Output: vm21616:1 Uncaught TypeError: Cannot read property 'name' of undefinedCopy the code

13. Shuffle an array

Utilize the built-in math.random () method.

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; List.sort (() => {return math.random () -0.5; }); / / output (9) [2, 5, 1, 6, 9, 8, 4, 3, 7] / / output (9) [4, 1, 7, 5, 3, 8, 2, 9, 6]Copy the code

14. Double question mark grammar

const foo = null ?? 'my school'; // output: "my school" const baz = 0? 42. // Output: 0Copy the code

Residual and expansion syntax

function myFun(a, b, ... manyMoreArgs) { return arguments.length; } myFun("one", "two", "three", "four", "five", "six"); // Output: 6Copy the code

and

const parts = ['shoulders', 'knees']; const lyrics = ['head', ...parts, 'and', 'toes']; lyrics; / / output: (5) [" head ", "shoulders", "knees", "and", "toes"]Copy the code

16. Default parameters

const search = (arr, low=0,high=arr.length-1) => { return high; } the search ([1, 2, 3, 4, 5]); // Output: 4Copy the code

Convert decimal to binary or hexadecimal

const num = 10; num.toString(2); // Output: "1010" num. ToString (16); // Output: "a" num. ToString (8); // output: "12"Copy the code

18. Use deconstruction to swap two numbers

let a = 5; let b = 8; [a,b] = [b,a] [a,b]Copy the code

19. Check the palindrome number of a single line

function checkPalindrome(str) { return str == str.split('').reverse().join(''); } checkPalindrome('naman'); // Output: trueCopy the code

20. Convert the Object property to an array of properties

const obj = { a: 1, b: 2, c: 3 };

Object.entries(obj);
// Output
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3

Object.keys(obj);
(3) ["a", "b", "c"]

Object.values(obj);
(3) [1, 2, 3]
Copy the code

~ end, I am small wisdom, we will see you next time!


Original text: dev. The to/techygeeky /…

communication

This article is updated weekly, you can search wechat ** [big move the world] the first time to read, reply [welfare] ** there are many front-end video waiting for you, this article GitHub github.com/qq449245884… Already included, welcome Star.