Git Product home page Git Product logo

arraytoheavy's Introduction

ArrayToHeavy

数组去重

第一种方法 method1.js

  • 构建一个新的数组存放结果
  • for循环中每次从原数组中取出一个元素,用这个元素循环与结果数组对比
  • 若结果数组中没有该元素则存放到结果数组中

第二种方法

  • 先将原数组排序
  • 构建一个新的结果数组
  • 检查原数组中的第i个元素,与结果数组中的最后一个元素是否相同,因为已经排序,所以重复元素会在相邻的位置。
  • 如果不同,则将该元素存入结果数组中

第三种方法 hash map

  • 构建一个新的数组存放结果
  • 创建一个空对象
  • for循环的时候,每次取出来一个与元素与对象进行对比,如果这个元素不重复,则把它放到结果数组里,同时,把这个元素的内容作为对象的一个属性,并且赋值为1(随意), 然后存入上面创建的对象中。

每次从原数组中取出一个元素,然后到对象中去访问这个属性,如果能访问到,就说明是重复的。与方法一相比,优势在于,少了一重循环。但是对象的key默认被转为字符串


第四种方法 es6 set

  • 生成一个Set的实例对象
  • 遍历原来的数组,将其元素添加到上面步骤的集合中

Set,是es6提供的一种新的数据结构,类似于数组,但是它的成员都是唯一的,没有重复的值。可以接收一个数组或者类数组对象,自动去重其中的重复项目。

Set本身是一个构造函数,用来生成Set数据结构。

add() 方法将元素添加到匹配元素的集合中。

arraytoheavy's People

Contributors

hcyfreedom avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.