First, for data operation

1. Array deduplication

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); 

> Result:(4) [1, 2, 3, 5]
Copy the code

This is a new feature in ES6, and prior to ES6, we needed to use more code to achieve the same effect. This technique applies to arrays containing basic types: undefined, NULL, Boolean, String, and number.

In addition to the above method, you can also use array.from (new Set()) :

const array = [1, 1, 2, 3, 5, 5, 1]
Array.from(new Set(array))

> Result:(4) [1, 2, 3, 5]
Copy the code

Alternatively, we can use the.filter and indexOf() values of Array:

const array = [1, 1, 2, 3, 5, 5, 1]
array.filter((arr, index) => array.indexOf(arr) === index)

> Result:(4) [1, 2, 3, 5]
Copy the code

Note that the indexOf() method returns the first occurrence of the array item. This is why we can compare the index returned by the indexOf() method with the current item in each iteration to determine if the current item is duplicated.

2. Array mapping

Array.from method operation

Const array = [{name: 'desert ', email: '[email protected]'}, {name: 'Airen', email: '[email protected]'}] const name = array. from(Array, ({name}) => name) > Result: (2) [" dA ", "Airen"]Copy the code

3. Array truncation

If you want to delete a value from the end of the array (deleting the last item in the array), there are faster alternatives than using splice().

For example, if you know the size of the original array, you can redefine the value of the length property of the array to remove the value from the end of the array:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(array.length)
> Result: 10

array.length = 4
console.log(array)
> Result: (4) [0, 1, 2, 3]
Copy the code

This is a particularly neat solution. However, the slice() method runs faster and performs better:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);

console.log(array); 
> Result: [0, 1, 2, 3]
Copy the code

Filter out the falsy value in the array

If you want to filter falsy values in an array, such as 0, undefined, null, false, you can use map and filter methods:

Const array = [0, 1, '0', '1', 'w3cplus.com', undefined, true, false, null, 'undefined', 'null', NaN, 'NaN', '1' + 0] array.map(item => { return item }).filter(Boolean) > Result: (10) [1, "0", "1", "desert", "w3cplus.com", true, "undefined", "null", "NaN", "10"]Copy the code

5. Get the last item of the array

When slice() is a positive value, items are retrieved from the beginning of the array. When slice() is a negative integer, items are retrieved from the end of the array.

let array = [1, 2, 3, 4, 5, 6, 7]

const firstArrayVal = array.slice(0, 1)
> Result: [1]

const lastArrayVal = array.slice(-1)
> Result: [7]

console.log(array.slice(1))
> Result: (6) [2, 3, 4, 5, 6, 7]

console.log(array.slice(array.length))
> Result: []
Copy the code

Slice (-1) is used to retrieve the last item of the array, as shown in the example above. In addition to retrieving the last item of the array, you can use the following method:

console.log(array.slice(array.length - 1))
> Result: [7]
Copy the code

6. Filter and sort the string list

You may have a list of many names and need to filter out duplicate names and sort them alphabetically.

var keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'var', 'case', 'else', 'enum', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'delete', 'export', 'import', 'return', 'switch', 'typeof', 'default', 'extends', 'finally', 'continue', 'debugger', 'function', 'do', 'if', 'in', 'for', 'int', 'new', 'try', 'var', 'byte', 'case', 'char', 'else', 'enum', 'goto', 'long', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'final', 'float', 'short', 'super', 'throw', 'while', 'delete', 'double', 'export', 'import', 'native', 'public', 'return', 'static', 'switch', 'throws', 'typeof', 'boolean', 'default', 'extends', 'finally', 'package', 'private', 'abstract', 'continue', 'debugger', 'function', 'volatile', 'interface', 'protected', 'transient', 'implements', 'instanceof', 'synchronized', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'await', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof'];
Copy the code

Since we don’t want to change our original list, we’re going to use a higher-order function called filter, which will return a new filtered array based on the callback method we passed. The callback method compares the index of the current keyword in the original list with the index in the new list, and pushes the current keyword into the new array only if the index matches.

Finally, we are ready to sort the filtered list using the sort method, which takes only one comparison method as an argument and returns the list sorted alphabetically.

Using the arrow function in ES6 looks simpler:

const filteredAndSortedKeywords = keywords .filter((keyword, index) => keywords.lastIndexOf(keyword) === index) .sort((a, b) => a < b ? 1:1);Copy the code

Here is the list of JavaScript reserved words after final filtering and sorting:

console.log(filteredAndSortedKeywords);

> Result: ['abstract', 'arguments', 'await', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'double', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'final', 'finally', 'float', 'for', 'function', 'goto', 'if', 'implements', 'import', 'in', 'instanceof', 'int', 'interface', 'let', 'long', 'native', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'true', 'try', 'typeof', 'var', 'void', 'volatile', 'while', 'with', 'yield']
Copy the code

7. Empty the array

If you define an array and you want to empty it. Usually, you do this:

let array = [1, 2, 3, 4];
function emptyArray() {
    array = [];
}
emptyArray();
Copy the code

However, there is a more efficient way to empty the array. You can write:

let array = [1, 2, 3, 4];
function emptyArray() {
    array.length = 0;
}
emptyArray();
Copy the code

8. Flatten multidimensional arrays

The use of… Operator to flatten a multidimensional array:

Const arr = [1, 2, 'the desert'], 3, [' blog ', '1', 2, 3]] const flatArray = [] concat (... Arr) console. The log (flatArray) > Result: (8) [1, 2, "desert", 3, "blog", "1", 2, 3]Copy the code

But the above method only works with two-dimensional arrays. But with recursive calls, you can use it for arrays up to two dimensions:

function flattenArray(arr) { const flattened = [].concat(... arr); return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened; } const array = [1, 2, 'the desert'], 3, and [[' blog ', '1'], 2, [1]] const flatArr = flattenArray(array) console.log(flatArr) > Result: (1) [1, 2, "blog", "1", 2, 3]Copy the code

9. Get the maximum and minimum values from the array

We can use math. Max and math. min to fetch the maximum and minimum values in the array:

const numbers = [15, 80, -9, 90, -99]
const maxInNumbers = Math.max.apply(Math, numbers)
const minInNumbers = Math.min.apply(Math, numbers)

console.log(maxInNumbers)
> Result: 90

console.log(minInNumbers)
> Result: -99
Copy the code

You can also use ES6’s… Operator to accomplish:

const numbers = [1, 2, 3, 4]; Math.max(... numbers) > Result: 4 Math.min(... numbers) > > Result: 1Copy the code

2. Operate on objects

There are also a few tricks to manipulating objects.

1. Use… The operation conforms to an object in a union object or array

Also using ES… Operators can replace manual operations by merging objects or objects in arrays.

// Merge object const obj1 = {name: ' ', url: 'w3cplus.com'} const obj2 = {name: 'airen', age: 30} const mergingObj = {... obj1, ... Obj2} > Result: {name: "airen", url: "w3cplus.com", age: 30} '[email protected]' }, { name: 'Airen', email: '[email protected]' } ] const result = array.reduce((accumulator, item) => { return { ... Accumulator, [item.name]: item.email}}, {}) > Result: {desert: "[email protected]", Airen: "[email protected]"}Copy the code

2. Add object attributes conditionally

It is no longer necessary to create two different objects based on a condition so that it has specific properties. To do this, use… The operator is the simplest.

Const getUser = (emailIncluded) => {return {name: 'w3cPlus ', blog:' w3cPlus ',... emailIncluded && {email: '[email protected]'} } } const user = getUser(true) console.log(user) > Result: {name: "Da Mo ", blog:" W3CPlus ", email: "[email protected]"} const userWithoutEmail = getUser(false) console.log(userWithoutEmail) > Result: {name: "Desert ", blog: "w3cplus"}Copy the code

3. Determine the object’s data type

Use Object. The prototype. ToString cooperate closure to realize the Object data type:

const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isArray = isType('Array')([1, 2, 3])

console.log(isArray)
> Result: true
Copy the code

The code above is equivalent to:

function isType(type){
    return function (target) {
        return `[object ${type}]` === Object.prototype.toString.call(target)
    }
}

isType('Array')([1,2,3])
> Result: true
Copy the code

Or:

const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isString = isType('String')
const res = isString(('1'))

console.log(res)
> Result: true
Copy the code

4. Create a pure object

Use object.create (null) to create a pure Object that inherits no methods from Object (such as constructors, toString(), etc.) :

const pureObject = Object.create(null);

console.log(pureObject);                //=> {}
console.log(pureObject.constructor);    //=> undefined
console.log(pureObject.toString);       //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined
Copy the code

Data type conversion

In JavaScript, data types include Number, String, Boolean, Object, Array, Function, etc. In practice, conversion of data types will be encountered. There are also a few tricks when converting data types.

1. Convert to a Boolean value

In addition to Boolean values true and false, JavaScript can treat all other values as “true” or “false.” Values other than 0, “, null, undefined, NaN, and false are true in JavaScript unless otherwise defined.

const isTrue = ! 0; const isFasle = ! 1; const isFasle = !! 0 / /! Log (isTrue) > Result: true console.log(typeof isTrue) > Result: 'Boolean'Copy the code

2. Convert to a string

We can quickly convert numbers or booleans to strings using the operator + followed by an empty set of quotes:

const val = 1 + ''
const val2 = false + ''

console.log(val)
>  Result: "1"

console.log(typeof val)
> Result: "string"

console.log(val2)
> Result: "false"

console.log(typeof val2)
> Result: "string"
Copy the code

3. Convert to a value

As we saw above, a numeric value can be converted to a string using + followed by an empty string “. Conversely, using the addition operator + can quickly achieve the opposite effect.

let int = '12'
int = +int

console.log(int)
> Result: 12

console.log(typeof int)
> Result: 'number'
Copy the code

A Boolean value can be converted to a numeric value in the same way:

console.log(+true)
> Return: 1

console.log(+false)
> Return: 0
Copy the code

In some contexts, + is interpreted as the join operator, not the addition operator. When this happens and you want to return an integer rather than a floating-point number, you can use two tilde ~~.

4. Hacker method

1, the Replace All

We know that string.replace () only replaces the first item.

You can replace everything with /g at the end of the regular expression.

var example = "potato potato";
console.log(example.replace(/pot/, "tom"));
// "tomato potato"
console.log(example.replace(/pot/g, "tom"));
// "tomato tomato"
Copy the code

2. Extract unique values

We can use the Set object and the Spread operator to create a new array that strips out duplicate values.

var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8]
Copy the code

3. Convert numbers to strings

We simply use the concatenation operator with empty quotes.

var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string
Copy the code

4. Convert strings to numbers

Use the + operator.

Note the usage here, as it only applies to “string numbers”.

the_string = "123";
console.log(+the_string);
// 123
the_string = "hello";
console.log(+the_string);
// NaN
Copy the code

5. Arrange the elements of the array randomly

Every day I’m lining up at random…

var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; Console. log(my_list.sort(function() {return math.random () -0.5})); // [4, 8, 2, 9, 1, 3, 6, 5, 7]Copy the code

6. Flatten multidimensional arrays

Just use the Spread operator.

var entries = [1, [2, 5], [6, 7], 9]; var flat_entries = [].concat(... entries); // [1, 2, 5, 6, 7, 9]Copy the code

7. Short circuit conditions

Here’s an example:

if (available) {
    addToCart();
}
Copy the code

It can be shortened simply by using variables and functions:

available && addToCart()
Copy the code

8. Use length to resize/empty the array

It basically overrides the length of the array.

If we want to resize the array:

var entries = [1, 2, 3, 4, 5, 6, 7];
console.log(entries.length);
// 7
entries.length = 4;
console.log(entries.length);
// 4
console.log(entries);
// [1, 2, 3, 4]
Copy the code

If we want to empty the array:

var entries = [1, 2, 3, 4, 5, 6, 7]; console.log(entries.length); // 7 entries.length = 0; console.log(entries.length); // 0 console.log(entries); / / []Copy the code

Five, common basic operations

1. If statements with multiple conditions

//longhand
if (fruit === 'apple' || fruit === 'banana' || fruit === 'orange' || fruit ==='mango') {
    //logic
}

//shorthand
if (['apple', 'banana', 'orange', 'mango'].includes(fruit)) {
   //logic
}
Copy the code

2, the If… Else short for ternary operator

// Longhand
let mychoice: boolean;
if (money > 100) {
    mychoice= true;
} else {
    mychoice= false;
}

// Shorthand
let mychoice= (money > 10) ? true : false;
//or we can use directly
let mychoice= money > 10;
console.log(mychoice);
Copy the code

3. Variable declarations

//Longhand 
let data1;
let data2= 1;

//Shorthand 
let data1, data2= 1;
Copy the code

4. Check for non-null values (null, undefined, and null value checks)

What if we want to check that the variable is not empty? We can now get rid of writing all the conditions again.

// Longhand if (data1 ! == null || data1! == undefined || data1 ! == '') { let data2 = data1; } // Shorthand let data2 = data1 || '';Copy the code

5, empty check

One of the most commonly used operands, but make sure your value is true, a non-empty string, a defined value, and a non-null value.

// Longhand if (data1 === true) or if (data1 ! == "") or if (data1 ! == null) // Shorthand // if (test1)Copy the code

6. The AND(&&) operator

This technique can be helpful if we want to avoid missing an if statement.

//Longhand 
if (test1) {
 callMethod(); 
}

//Shorthand 
test1 && callMethod();
Copy the code

7. Return to the shorthand

This will help avoid the need to use a lot of code to specifically return to the call method based on the return statement.

// Longhand let value; function returnMe() { if (! (value === undefined)) { return value; } else { return callFunction('value'); } } var data = returnMe(); console.log(data); //output value function callFunction(val) { console.log(val); } // Shorthand function returnMe() { return value || callFunction('value'); }Copy the code

8. Switch statement optimization

If you want to optimize your switch statements, this will help.

// Longhand
switch (data) {
    case 1:
        data1();
        break;
    case 2:
        data2();
        break;
    case 3:
        data();
        break;
        // And so on...
}

// Shorthand
var data = {
    1: data1,
    2: data2,
    3: data
};
const val = 1
data[val]();
function data1() {
    console.log("data1");
}
function data2() {
    console.log("data2");
}
function data() {
    console.log("data");
}
Copy the code

9. Propagation operators

It is also useful to create array references and shallow copies in another place.

//longhand // joining arrays using concat const testdata= [1, 2, 3]; const values = [4 ,5 , 6].concat(data); //shorthand // joining arrays const testdata = [1, 2, 3]; const values = [4 ,5 , 6, ...testdata]; console.log(test); // [4, 5, 6, 1, 2, 3]Copy the code

For cloning, we can also use extended operators.

//longhand
// cloning arrays
const data1 = [1, 2, 3];
const data2 = data1.slice()

//shorthand
// cloning arrays
const data1 = [1, 2, 3];
const data2 = [...data1];
Copy the code

10. Digital conversion

//Longhand let test1 = parseInt('12'); Let test2 = parseFloat (' 2.33 '); //Shorthand let test1 = +'12'; Let test2 = + '2.33';Copy the code

11. Deconstruct assignment

//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;

//shorthand
const { test1, test2, test3 } = this.data;
Copy the code