This article documents some common operations and tricks on arrays in JS and will be updated continuously.

Find the maximum and minimum values in arrays and array objects

Array deduplication

Find the maximum and minimum values in arrays and array objects

1. Temporary variables are iterated through

// The minimum value is similar
Array.prototype.max = function() { 
	var max = this[0];
	for (var i = 1; i < this.length; i++){ 
		if (this[i] > max) { 
			max = this[i]; }}return max;
}

var arr = [3.6.1.8.12.5];
arr.max();  / / 12
Copy the code

If you are introducing a utility class library and fear that the library also implements a prototype method of the same name, you can use the same name before adding a function:

if (typeof Array.prototype['max'= = ='undefined') { 
	Array.prototype.max = function() {... }}Copy the code

Math.max and math.min

The math. Max or math. min methods can be used to find the maximum and minimum values, but instead of taking an array, they take strings separated by, so with the apply method, its first argument is the value to bind to this and its second argument is an array.

Array.prototype.max = function( array ){ 
	return Math.max.apply( Math, array ); // Here, we don't need to change the this pointer, the important thing is to pass our target array to the second parameter
};
Copy the code

3. Multidimensional arrays

If it’s a multi-dimensional array, what’s the maximum or minimum? It’s easy, it’s all the same, you take a multidimensional array and convert it to a one-dimensional array and evaluate it.

var arr = [8.5.1[9.6], [2.10.8[11.3]].var target = arr.join(",").split(","); // Convert to a one-dimensional array
Math.max.apply(null,target); / / Max
Copy the code

4. Array objects

For example, we have the following array objects:

var arr = [
	{name: 'zhangsan'.age: 18},
	{name: 'lisi'.age: 20},
	{name: 'wangwu'.age: 17}];Copy the code

Find the maximum age:

Array.prototype.max = function () {
    if (this.length > 0) {
        var key = arguments[0];
        return Math.max.apply(Math.this.map(function (obj) {
                return obj[key]
           }));
    }
    return false;
}

arr.max('age'); / / 20
Copy the code

Array deduplication

1. Simplest method (using indexOf)

// Create a new array, newArr, and iterate over the array to be reduplicated. If the value is not in newArr (indexOf == -1), add it to the array
function unique(arr){
    var newArr = [];
    for(var i = 0; i < arr.length; i++){
        if(newArr.indexOf(arr[i]) == - 1){
            newArr.push(arr[i])
        }
    }
    return newArr;
}

var arr = [1.2.2.3.4.4.5.1.3];
var newArr = unique(arr); / / [1, 2, 3, 4, 5]
Copy the code

2. Take advantage of the fact that attributes of objects cannot be the same

function unique(arr){
    var newArr = [];
    var obj = {};
    for(var i=0; i<arr.length; i++){
       if(! obj[arr[i]]){ obj[arr[i]] =1; newArr.push(arr[i]); }}return newArr;
}
Copy the code

3. Use the Reduce method

Array.reduce (function(prev, cur, index, arr), init) it takes a callback and an initial value as arguments, where the callback takes four arguments: Init Initial value, which indicates the initial value when the reduce method is executed for the first time. This parameter is optional. Prev Specifies the return value of the last callback or the initial value init. This parameter is mandatory. Prev Initial value: init? Init: arr [0]; — 3. Cur Current value, array loop current value. This parameter is mandatory. The initial value of curr is also affected by init: init? Arr [0] : arr [1]. — 4. index Indicates the index of the current value processed by the array loop. The value of index changes synchronously with cur: init? 0:1; Arr The array currently being looped. Optional.

function unique(arr){
    return arr.reduce((prev, cur) = > {
    	returnprev.includes(cur) ? prev : prev.concat(cur); } []); }Copy the code

4. Use the filter method

Array. filter(function(currentValue,index,arr), thisValue) filter() Usually we just use the first parameter, which represents an element of the Array. The callback function can also take two additional arguments, representing the location of the element and the array itself.

function unique(arr){
    return arr.filter(function (cur, index, self) { &emsp; &emsp;returnself.indexOf(cur) === index; &emsp; &emsp; }); }Copy the code

5, use ES6 Set method

function unique(arr){
    //Set data structure, which is similar to an array in that its members have unique values
    return Array.from(new Set(arr)); // Convert a Set structure to an Array using array. from
}
Copy the code