Array to heavy

Arrays are often asked about in interviews or development, and I’ve sorted out four of them. Still have what new method, new operation, welcome complement!

var arr = [1.1.'1'.'1'.'true'.'true'.true.true.null.null.undefined.undefined.NaN.NaN, {'a': 1}, {'a': 1}]
Copy the code

1. The ES6 to heavy

{} cannot be deduplicated

Array.from(new Set(arr))
/ / (9) (1, "1", "true", true, null, and undefined, NaN, {...}, {...}]
Copy the code

2. Double traversal to remove weight

{}, NaN can not be repeated, can do special operations to achieve

function unique(arr = []) {
  for(let i = 0; i < arr.length; i++) {
    for(let j = i + 1; j < arr.length; j++) {
      if(arr[i] === arr[j]) {
        arr.splice(j, 1); j--; }}}}/ / (10) [1, "1", "true", true, null, and undefined, NaN, NaN, {...}, {...}]
Copy the code

3. De-weight indexOf or includes

Note that includes removes NaN, while indexOf does not.

arr.indexOf(NaN) === -1

function unique(arr = []) {
  let newArr = [];
  for(let i = 0; i < arr.length; i++) {
    debugger;
    if(! newArr.includes(arr[i]) || newArr.indexOf(arr[i]) ===- 1) { newArr.push(arr[i]); }}return newArr;
}
/ / (10) [1, "1", "true", true, null, and undefined, NaN, NaN, {...}, {...}]
Copy the code

4. The filter to heavy

Principle: indexOf only returns the location of the element when it first appears in an array

arr.filter((item, index, arr) = > {
  return arr.indexOf(item) === index;
})
(8) [1."1"."true".true.null.undefined, {... }, {... }]Copy the code