preface

Talk is cheap, show me the code. That’s an interesting sentence.

Basic type array deduplication

1, the most direct efficient method [extension operator + Set()]

In the actual work, this method is recommended to use directly to go heavy, convenient and affordable. A Set object is a collection of values, and you can iterate over its elements in the order in which they were inserted. Elements in a Set occur only once, that is, the elements in a Set are unique.

function removeDuplicate_1(arr) {
  return [... new Set(arr)]
}
Copy the code

Let set = new set (arr); return [… set]; Where set is a collection object, set is used by… Structuring each item into an array.

2. Use the array API reduce method.

If (prev. IndexOf (cur) === -1) = indexOf(); if(prev.

function removeDuplicate_2(arr) {
  arr.sort((a, b) = > a - b) // Sort arrays in ascending order
  return  arr.reduce((prev, cur) = > { // return the result of prev
  / / array is empty for the first time | | prev array of the last item is not equal to arr next item, put the current item cur push to prev array,
    if (prev.length === 0 || (prev[prev.length - 1] !== cur)) { 
      prev.push(cur)
    }
    return prev;  // The returned prev becomes the new value of reduce(prev,cur)}}, [])Copy the code

Reduce Method Introduction

Arr. Reduce ((p,c)=>{fn content; Return p},init).

Summary: The reduce parameter consists of a function and an initial value. The initial value is optional. The function has four parameters to choose from. PreviousValue = initialValue (initialValue), currentValue = arr[0], p = arr[0], c = arr[1] The result of return is the initial value of p for the next iteration.

  • A “Reducer” function with four parameters:

    • previousValue: Last callcallbackFnIs the return value of On the first call, if an initial value is specifiedinitialValue, and its value isinitialValueOtherwise, the element with an array index of 0array[0].
    • currentValue: The element being processed in the array. On the first call, if an initial value is specifiedinitialValue, whose value is the element with an array index of 0array[0], or forarray[1].
    • currentIndex: Index of the element being processed in the array. If an initial value is specifiedinitialValue, the start index is 0; otherwise, the start index is 1.
    • array: An array for traversal.
  • The initialValue optional

  • As the value of the previousValue argument when the callback function is first called. If initialValue is specified, currentValue will use the first element of the array; Otherwise, previousValue will use the first element of the array, and currentValue will use the second element of the array.

use

1. Find the sum of all the values of the array

let sum = [0.1.2.3].reduce(function (previousValue, currentValue) {
  return previousValue + currentValue
}, 0)
// sum is 6

Copy the code

2. Add the values in the array of objects

let initialValue = 0
let sum = [{x: 1}, {x: 2}, {x: 3}].reduce(
    (previousValue, currentValue) = > previousValue + currentValue.x
    , initialValue
)

console.log(sum) // logs 6

Copy the code

See official documentation for more examples

How does reduce() run without an initial value

Suppose we run the following reduce() code with no initial value:

const array = [15.16.17.18.19];

function reducer(previous, current, index, array) {
  const returns = previous + current;
  console.log(`previous: ${previous}, current: ${current}, index: ${index}, returns: ${returns}`);
  return returns;
}

array.reduce(reducer);
Copy the code

Callback is called four times, and the parameters and return values of each call are as follows:

callback iteration previousValue currentValue currentIndex array return value
first call 15 16 1 [15, 16, 17, 18, 19] 31
second call 31 17 2 [15, 16, 17, 18, 19] 48
third call 48 18 3 [15, 16, 17, 18, 19] 66
fourth call 66 19 4 [15, 16, 17, 18, 19] 85

The value returned by reduce() will be the last callback return value (85).

How does reduce() work with an initial value

Here, we use the same algorithm reduce for the same array, but provide 10 as the initial value:

[15.16.17.18.19].reduce( (previousValue, currentValue, currentIndex, array) = > previousValue + currentValue, 10 )
Copy the code

Copy to Clipboard

callback iteration previousValue currentValue currentIndex array return value
first call 10 15 0 [15, 16, 17, 18, 19] 25
second call 25 16 1 [15, 16, 17, 18, 19] 41
third call 41 17 2 [15, 16, 17, 18, 19] 58
fourth call 58 18 3 [15, 16, 17, 18, 19] 76
fifth call 76 19 4 [15, 16, 17, 18, 19] 95

Reduce () returns 95 in this case.

3. Use a for loop to solve the problem

1, declare a new array result to hold the new array.

2. Sort the array.

Arr [-1] = arr[-1]; arr[-1] = arr[-1]; arr[-1] = arr[-1]; So you can do this, think about (1), if(arr[I]! == arr[I + 1]) Can you say your answer in the comment section, why?

4, Return result

function removeDuplicate_3(arr) {
  let result = []
  arr.sort((a, b) = > a - b)
  for (let i = 0; i < arr.length; i++) {
    if(arr[i] ! == arr[i -1]) {
      result.push(arr[i])
    }
  }
  return result
}
Copy the code

Sort Method Introduction

 arr.sort((a, b) = > a - b) / / ascending
  arr.sort((a, b) = > b - a) / / descending
Copy the code

4. Use the array API indexOf() method

function removeDuplicate_4(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (result.indexOf(arr[i]) == -1) {
      result.push(arr[i])
    }
  }
  return result;
}
Copy the code

Introduction to the indexOf() method

The indexOf() method returns the first index in the array where a given element can be found, or -1 if none exists. Summary: Takes two arguments and returns the subscript value. Arr.indexof (Element to search, search from that location)

The sample

var array = [2.5.9];
array.indexOf(2);     / / 0
array.indexOf(7);     // -1
array.indexOf(9.2);  / / 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); / / 0

Copy the code

The indexOf() method is described in detail

5. Use the Array API array.from () method and the Set object

function removeDuplicate_5(arr) {
  return Array.from(new Set(arr))
}
Copy the code

The array.from () method creates a new, shallow-copy instance of an array-like or iterable.

Summary: Takes three arguments and returns an array. Array.from(array-like object to process, fn (callback function optional), this (callback function this refers to, optional))

Note: Array.from is used, not Array instance arr.from, as Java static methods are called by class names.

Array.from () details

6. Use a for loop to take advantage of the storage properties of objects

function removeDuplicate_6(arr) {
  let result = [], obj = {};
  for (let item of arr) {
    if(! obj[item]) { result.push(item); obj[item] =1
    } else {
      obj[item]++
    }
  }
  return result;
}
Copy the code

7. Use the array API Filter and indexOf methods in conjunction with the prototypical this call

function removeDuplicate_7(arr) {
  return Array.prototype.filter.call(arr, (item, index) = > {
    return arr.indexOf(item) === index
  })
}

Copy the code

8, use the array of fast and slow Pointers

function removeDuplicate_8(arr) {
  let fast = 0, low = -1, result = [];
  arr.sort((a,b) = > a - b)
  while (fast < arr.length) {
    if(arr[fast] ! == arr[low]) { result.push(arr[fast]) } fast++ low++ }return result;
}
Copy the code

Unduplicate array object types

Use filter and Map to remove objects from the array

The Map object holds key-value pairs and can remember the original insertion order of the keys. Any value (object or raw value) can be a key or a value. Map object

The filter() method creates a new array containing all the elements of the test implemented through the provided function.


let arr_obj = [
  {
    id: 1.name: 'Joe'.age: 18.sex: 1
  },
  {
    id: 2.name: 'bill'.age: 20.sex: 2
  },
  {
    id: 1.name: 'Joe'.age: 18.sex: 1
  },
  {
    id: 3.name: 'Wang Lao Wu'.age: 18.sex: 2
  },
  {
    id: 4.name: 'Wang Lao Wu'.age: 18.sex: 2}]function removeDuplicate_10(arr, attr) {
  const result = new Map(a);return arr.filter((item) = >! result.has(item[attr]) && result.set(item[attr],1))}console.log(arr_obj);
console.log(removeDuplicate_10(arr_obj, 'name')); // Delete the object name
Copy the code

Is the content in filter() above hard to understand? It equals


function removeDuplicate_11(arr, attr) {
  const result = new Map(a);let fn = (item) = > {
    if(! result.has(item[attr])) {return result.set(item[attr], 1)}}return arr.filter(fn)
}
Copy the code

! Result. has(item[attr]) && result.set(item[attr], 1)

 if(! result.has(item[attr])) { result.set(item[attr],1)}// The arrow function does not have {} curly braces, so it returns, so it would look like this
  if(! result.has(item[attr])) {return result.set(item[attr], 1)}Copy the code

Before going to weight

[{id: 1.name: 'Joe'.age: 18.sex: 1 },
  { id: 2.name: 'bill'.age: 20.sex: 2 },
  { id: 1.name: 'Joe'.age: 18.sex: 1 },
  { id: 3.name: 'Wang Lao Wu'.age: 18.sex: 2 },
  { id: 4.name: 'Wang Lao Wu'.age: 18.sex: 2}]Copy the code

After go to heavy

[{id: 1.name: 'Joe'.age: 18.sex: 1 },
  { id: 2.name: 'bill'.age: 20.sex: 2 },
  { id: 3.name: 'Wang Lao Wu'.age: 18.sex: 2}]Copy the code

Id to heavy

console.log(removeDuplicate_8(arr_obj, 'id')); [{id: 1.name: 'Joe'.age: 18.sex: 1 },
  { id: 2.name: 'bill'.age: 20.sex: 2 },
  { id: 3.name: 'Wang Lao Wu'.age: 18.sex: 2 },
  { id: 4.name: 'Wang Lao Wu'.age: 18.sex: 2}]Copy the code

10. Use the array method reduce and object features

The idea is to create an empty object, determine if it has a value for that property, and push it to array storage if it doesn’t

function removeDuplicate_12(arr, attr) {
  let obj = {}
  return arr.reduce((prev,curr) = >{
    // If () {// if () {// if () {// if ();
    obj[curr[attr]] ? ' ' : obj[curr[attr]] = true && prev.push(curr) // "is empty
     // it can also be undefined
    // obj[curr[attr]] ? undefined : obj[curr[attr]] = true && prev.push(curr)
    return prev
  },[])
}
console.log(removeDuplicate_12(arr_obj, 'name'));
Copy the code

11. Use the for of loop plus object feature.

The idea is similar to that of 9, but the knowledge iteration is different.

function removeDuplicate_13(arr, attr) {
  let obj = {}, result = [];
  for(let item of arr){
    if(! obj[item[attr]]) { result.push(item) obj[item[attr]] =true}}return result;
}
console.log(removeDuplicate_13(arr_obj, 'id'));
Copy the code

References to related articles

JS object array to duplicate three methods

Array to heavy