Two methods for JavaScript array to go heavy recommend _javascript techniques

Source: Internet
Author: User
Tags javascript array

1, the array to weight;

The array type does not provide a way to repeat, if you want to kill the repeating elements of the array, you have to do it yourself:

Method One: Using IndexOf method;

var aa=[1,3,5,4,3,3,1,4]
function arr (arr) {
  var result=[] for
  (var i=0; i<arr.length; i++) {
    if ( Result.indexof (Arr[i]) ==-1) {
      result.push (Arr[i])
    }
  console.log
  (Result)}      
arr (aa)

Method Two:

function Unique (arr) {
  var result = [], isrepeated;
  for (var i = 0, len = arr.length i < len; i++) {
    isrepeated = false;
    for (var j = 0, Len = result.length J < Len; J + +) {
      if (arr[i] = Result[j]) {  
        isrepeated = true;
        break;
      }
    }
    if (!isrepeated) {
      result.push (arr[i]);
    }
  return result;
}

method Two, the overall idea is to move the elements of the array to another array, the process of handling to check whether there is duplication, if there is a direct throw away. It can be seen from nested loops that this method is extremely inefficient. We can use a Hashtable structure to record existing elements so that the inner loops can be avoided. Exactly, implementing Hashtable in JavaScript is extremely simple, as follows:

function Unique (arr) {
  var result = [], hash = {};
  for (var i = 0, elem; (Elem = arr[i])!= null; i++) {
    if (!hash[elem]) {
      result.push (elem);
      Hash[elem] = true;
    }
  }
  return result;
}

Above this JavaScript array to weight two methods recommended is to share all the content of the small, hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.