Array to heavy

Double cycle weight removal

For (or while) with a double loop is a clumsy way, its implementation principle is simple: first define an array containing the first element on the original array, and then traverse the original array, each element from the original array and compare the new each element of the array, if you don’t repeat is added to the new array, finally return to the new array; Because it’s O(n^2) in time, if the array is large, it’s going to be very memory intensive

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error! ')
        return
    }
    let res = [arr[0]]
    for (let i = 1; i < arr.length; i++) {
        let flag = true
        for (let j = 0; j < res.length; j++) {
            if (arr[i] === res[j]) {
                flag = false;
                break}}if (flag) {
            res.push(arr[i])
        }
    }
    return res
}

Copy the code

The indexOf method removes 1

The indexOf() method of an array returns the first occurrence of a specified element in the array. This method first defines an empty array RES, and then calls indexOf to traverse the original array. If the element is not in res, it is pushed into RES. Finally, the res is returned to obtain the de-duplicated array

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error! ')
        return
    }
    let res = []
    for (let i = 0; i < arr.length; i++) {
        if (res.indexOf(arr[i]) === -1) {
            res.push(arr[i])
        }
    }
    return res
}


Copy the code

The indexOf method removes the weight of 2

IndexOf is used to check whether the first occurrence position of an element in the array is the same as the current position of the element. If not, the element is a duplicate element

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error! ')
        return
    }
    return Array.prototype.filter.call(arr, function(item, index){
        return arr.indexOf(item) === index;
    });
}

Copy the code

Adjacent elements are deduplicated

This method first calls sort(), and then traverses and aligns adjacent elements based on the sorted result. If they are equal, the elements are skipped until the traversal is complete

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error! ')
        return
    }
    arr = arr.sort()
    let res = []
    for (let i = 0; i < arr.length; i++) {
        if(arr[i] ! == arr[i-1]) {
            res.push(arr[i])
        }
    }
    return res
}

Copy the code

Use object attributes to de-weigh

Create an empty object, iterate through the array, set the value in the array to an attribute of the object, and assign the initial value of the attribute 1. Each occurrence increases the corresponding attribute value by 1, so that the attribute value corresponds to the number of occurrences of the element

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error! ')
        return
    }
    let res = [],
        obj = {}
    for (let i = 0; i < arr.length; i++) {
        if(! obj[arr[i]]) { res.push(arr[i]) obj[arr[i]] =1
        } else {
            obj[arr[i]]++
        }
    }
    return res
}

Copy the code

Set and deconstruction assignment deduplicating

The data type set is new in ES6. One of the biggest features of a set is that data does not duplicate. The Set function can take an array (or array-like object) as an argument to initialize, which can also be used to deduplicate arrays

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error! ')
        return
    }
    return [...new Set(arr)]
}

Copy the code

Array.from and set are de-duplicated

The array. from method converts a Set structure into an Array result, and we know that the Set result is a non-repeating data Set, so it can be de-duplicated

function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error! ')
        return
    }
    return Array.from(new Set(arr))
}

Copy the code

join & split

const colors = 'green, red, black'; const colorsArr = colors.split(','); console.log(colorsArr); // [ 'green', ' red', ' black' ] const colorsStr = colorsArr.join(','); console.log(colorsStr); // green, red, black copies the codeCopy the code

push & pop

const colors = []; colors.push('green', 'red'); console.log(colors); // ['green', 'red'] const item = colors.pop(); console.log(item); // 'red' console.log(colors); // ['green'] copies the codeCopy the code

shift & unshift

const colors = ['green', 'red']; const item = colors.shift(); console.log(item); // 'green' console.log(colors); // ['red'] colors.unshift('blue', 'grey'); console.log(colors); // ['blue', 'grey', 'red'] copies the codeCopy the code

reverse & sort

const values = [1, 3, 44, 43, 654, 0]; values.reverse(); console.log(values); // [ 0, 654, 43, 44, 3, 1 ] values.sort(); console.log(values); // [0, 1, 3, 43, 44, 654] values. Sort ((val1, val2) => val2-val1); console.log(values); // [654, 44, 43, 3, 1, 0] copy codeCopy the code

concat, slice & splice

const colors = ['red', 'green', 'blue']; const colors2 = colors.concat('yellow', ['black']); console.log(colors2); // [ 'red', 'green', 'blue', 'yellow', 'black' ] const colors3 = colors2.slice(1, 5); console.log(colors3); // [ 'green', 'blue', 'yellow', 'black' ] console.log(colors2); // [ 'red', 'green', 'blue', 'yellow', 'black' ] const remove1 = colors2.splice(0, 1); console.log(remove1); // [ 'red' ] console.log(colors2); // [ 'green', 'blue', 'yellow', 'black' ] const remove2 = colors2.splice(1, 0, 'red', 'pink'); console.log(remove2); // [ ] console.log(colors2); / / [' green ', 'red', 'pink', 'blue', 'yellow', 'black'] to copy codeCopy the code

indexOf & lastIndexOf

const values= [1, 3, 4, 6, 7, 4, 3, 1]; console.log(values.indexOf(4)); // 2 console.log(values.lastIndexOf(4)); // 5 console.log(values.lastIndexOf(4, 4)); // 2 console.log(values.lastIndexOf(4, 5)); // copy the codeCopy the code

every, filter, forEach, map & some

every & some

const values = [1, 3, 4, 6, 7, 4, 3, 1]; const everyResult = values.every((item, index, array) => { return item > 2; }); console.log(everyResult); // false const someResult = values.some((item, index, array) => { return item > 2; }); console.log(someResult); // true copies the codeCopy the code

filter

const values = [1, 3, 4, 6, 7, 4, 3, 1]; const filterResult = values.filter((item, index, array) => { return item > 2; }); console.log(filterResult); // [ 3, 4, 6, 7, 4, 3 ] const obj = [ { num: 3 }, { num: 4 }, { num: 1 },{ num: 5 },{ num: 0 }, { num: 4 }]; const filterObjResult = obj.filter((item, index, array) => { return item.num > 2; }); console.log(filterObjResult); / / [{num: 3}, {num: 4}, {num: 5}, {num: 4}] duplicate codeCopy the code

map

const values = [1, 3, 4, 6, 7, 4, 3, 1]; const mapResult = values.map((item, index, array) => { return item * 2; }); console.log(mapResult); // [ 2, 6, 8, 12, 14, 8, 6, 2 ] const obj = [ { num: 3 }, { num: 4 }, { num: 1 },{ num: 5 },{ num: 0 }, { num: 4 }]; const mapObjResult = obj.map((item, index, array) => { return item.num; }); console.log(mapObjResult); // [3, 4, 1, 5, 0, 4Copy the code

forEach

const values = [1, 3, 4, 6, 7, 4, 3, 1]; values.forEach((item, index, array) => { array[index] = item * 2; }); console.log(values); // [2, 6, 8, 12, 14, 8, 6, 2] copy codeCopy the code

reduce & reduceRight

const values = [1, 3, 4, 4, 4, 9]; const sum = values.reduce((prev, cur, index, array) => { return prev + cur; }); console.log(sum); // 25 const sumRight = values.reduceRight((prev, cur, index, array) => { return prev + cur; }); console.log(sumRight); / / 25Copy the code

Extended operator.

const colors = ['green', 'red', 'pink']; const colors1 = ['white', 'grey']; const colors2 = [...colors, ...colors1]; console.log(colors2); / / [' green ', 'red', 'pink', 'white', 'grey'] to copy codeCopy the code

Array.from() & Array.of()

const obj = { '0': '123', '1': '456', '2': 'c', length: 4 } const arr = Array.from(obj); console.log(arr); // [ '123', '456', 'c', undefined ] const values = [1, 1, 3, 5]; const setValue = new Set(values); const newArr = Array.from(setValue); [...new Set(values)] console.log(newArr); // [ 1, 3, 5 ] const newArr2 = Array.from(newArr, x => x * 2); console.log(newArr2); // [ 2, 6, 10 ] console.log(Array.of(undefined, 1, null)); // [undefined, 1, null] Copies codeCopy the code

copyWithin(target, start = 0, end = this.length)

If valid, start > end

const arr = [1, 3, 4, 4, 5, 8, 10, 1, 0].copyWithin(0, 3, 4); console.log(arr); // [ 4, 3, 4, 4, 5, 8, 10, 1, 0 ] const arr = [1, 3, 4, 4, 5, 8, 10, 1, 0].copyWithin(0, 3, 8); console.log(arr1); // [4, 5, 8, 10, 1, 8, 10, 1, 0Copy the code

fill

const colors = ['green', 'red', 'pink']; const colors1 = colors.fill('white'); console.log(colors1); // ['white', 'white', 'white'] copies the codeCopy the code

find & findIndex

const values = [1, 3, 4, 5, 6, NaN]; const findResult = values.find(num => num > 4 ); // undefined console.log(findResult); // 5 const findIndexResult = values.findIndex(num => num > 4 ); Log (findIndexResult); // 3 Copy codeCopy the code

entries(), keys() & values()

const colors = ["red", "green", "blue"];
for (const index of colors.keys()) {
  console.log(index); // 0 1 2
}

for (const ele of colors.values()) {
  console.log(ele); // red green blue
}
for (const [index, ele] of colors.entries()) {
  console.log(index, ele);
}
// 0 red
// 1 green
// 2 blue
Copy the code

includes

The second parameter is the starting position of the search

const values = [1, 3, 4, 5, 6, NaN];
console.log(values.includes(NaN)); // true
console.log(values.includes(4, 3)); // false
Copy the code

flat & flatMap

const values = [1, 2, [3, 4]].flat(); console.log(values); // [1, 2, 3, 4] const valuesDeep = [1, [2, [3]]]; console.log(valuesDeep.flat(Infinity)); / / [1, 2, 3]Copy the code