JS Array de-weight method

Source: Internet
Author: User
Tags object object

1. If no method is used, the initial wording should be:

functionUnique (arr) {varres=[];  for(vari=0,len=arr.length;i<len;i++){        varobj =Arr[i];  for(varJ=0,jlen = res.length;j<jlen;j++){            if(res[j]===obj) Break; }        if(jlen===j) Res.push (obj); }    returnRes;}vararr=[1,1, ' 2 ', ' 1 ', 3,4]arr=unique (arr); Console.log (arr);

2. If compatibility is not considered, the indexof () method of the array inside the ES5 is used.

function Unique (arr) {    var res =[];      for (var i=0,len=arr.length;i<len;i++) {        var obj = arr[i];         if (Res.indexof (obj) ===-1) Res.push (obj);    }     return Res;} var arr=[1,1, ' 2 ', ' 1 ', 3,4= unique (arr); Console.log (arr); // arr=[1, ' 2 ', ' 1 ', 3,4]

3. Using filter filtering in the ES5 array:

function Unique (a) {   var res = A.filter (function(item, index, array) {    return< /c7> Array.indexof (item) = = = index;  }    ); return Res;}   var a = [1, 1, ' 1 ', ' 2 ', 1]; var ans =

Method Two

The first method is to compare the elements in the original array with the elements in the result array, and we can change the idea of putting the last element of the repeating element in the original array into the result array.

function unique(a) {

var res = [];

for (var i = 0, len = a. Length; I < len; I+ +) {

for (var J = i + 1; J < Len; J+ +) {

//This step is very ingenious

//If the same element is found

//Then I self-increment into the next cycle comparison

if (a[i] = = = a[J])

J = + +i;

}

Res. Push(a[i]);

}

return res;

}

var a = [1, 1, ' 1 ', ' 2 ', 1] ;

var ans = unique(a);

Console. Log(ans); //= = ["1", "2", 1]

Although the complexity is still O (n^2), but you can see the result is different, 1 appears at the end of the array, because the result array takes the last occurrence of the element position.

Method Three (sort)

If the written interview only answer the above O (n^2) plan, may not be satisfied with the interviewer, the following is a few advanced programs.

After the array is sorted by sort, the same elements are theoretically placed in the adjacent position, then the elements in the front and back positions can be compared.

function unique(a) {

return a. Concat(). Sort(). Filter(function(item, pos, ary) {

return ! POS | | item! = ary[pos - 1];

});

}

var a = [1, 1, 3, 2, 1, 2 , 4];

var ans = unique(a);

Console. Log(ans); //= [1, 2, 3, 4]

But again, 1 and "1" will be lined up, and the different objects will be lined up, because their toString () will result in the same error:

var a = [1, 1, 3, 2, 1, 2< c22>, 4, ' 1 '];

var ans = unique(a);

Console. Log(ans); //= [1, 2, 3, 4]

Of course you can write this comparison function for the different types that might appear in the array. But it seems a bit troublesome.

Method Four (object)

The object object in JavaScript is used as a hash table, which is the solution of a written test several years ago, and like sort, you can go to an array that consists entirely of number primitive types.

function unique(a) {

var Seen = {};

return a. Filter(function(item) {

return seen. hasOwnProperty(item) ? false : (seen[item] = true);

});

}

var a = [1, 1, 3, 2, 1, 2, 4];

var ans = unique(a);

Console. Log(ans); //= [1, 3, 2, 4]

is still the same as the method three, because the key value of Object is a String type, so for 1 and "1" cannot be different, we can slightly improve, the type is also stored in key.

function unique(a) {

var ret = [];

var Hash = {};

for (var i = 0, len = a. Length; I < len; I+ +) {

var Item = a[i];

var key = typeof(item) + item;

if (hash[key] !== 1) {

ret. Push(item);

hash[key] = 1;

}

}

return ret;

}

var a = [1, 1, 3, 2, ' 4 ', 1 , 2, 4, ' 1 '];

var ans = unique(a);

Console. Log(ans); //= [1, 3, 2, "4", 4, "1"]

While solving the annoying 1 and "1" problems, there are other problems!

var a = [{name: ' Hanzichi '}, {age: +}, new String(1), new number (1)];

var ans = unique(a);

Console. Log(ans); //= = [Object, String]

But if the array elements are all number values of the underlying type, the key-value pair method should be the most efficient!

Method Five (ES6)

ES6 deployed Set and Array.from method, too powerful! If the browser supports this, you can do so:

function unique(a) {

return Array. From(new Set(a));

}

var a = [{name: ' Hanzichi '}, {age: +}, new String(1), new number (1)];

var ans = unique(a);

Console. Log(ans); //= = [Object, object, String, number]

_.unique

Finally, let's take a look at the implementation of underscore, underscore this encapsulation into the _.unique method, called _.unique (array, [issorted], [iteratee]). Where the first parameter is required, is the need to go to the heavy array, the second parameter is optional, if the array is ordered, you can pass in the Boolean value True, the third parameter is optional, if you need the result of an array iteration to go heavy, you can pass in an iterative function. and the array element de-weight is based on the = = = operator.

In fact, it is very simple, the implementation in underscore and the above method is similar.

Let's look at its core code:

for (var i = 0, length = getlength(array); I length; I+ +) {

var value = array[i],

//If an iteration function is specified

//The iteration of each element of the array

computed = iteratee ? iteratee(value, i, array) : value;

//If it is an ordered array, the current element can only be compared with the previous element

//Save the previous element with a seen variable

if (issorted) {

//If i = = 0, the direct push

//Otherwise compare whether the current element is equal to the previous element

if (! I | | seen !== computed) result. Push(value);

//Seen saves the current element for the next comparison

Seen = computed;

} Else if (iteratee) {

//If seen[] does not have computed this element value

if (! _. contains(seen, computed)) {

seen. Push(computed);

result. Push(value);

}

} Else if (! _. contains(result, value)) {

//If the iteration function is not used, the seen[] variable is not used.

result. Push(value);

}

}

The outer loop iterates through the array elements, and for each element, if the array is ordered, it is compared to the previous element, and if it is the same, it has already occurred and is not added to the result array, otherwise it is added. In the case of an iterative function, the value of the incoming iteration function is computed, the value is de-weighed, and the. Contains method is called, and the core of the method is called. The IndexOf method is the same as the method we said above.

For detailed code on the _.unique method, refer to https://github.com/hanzichi/underscore-analysis/blob/master/underscore-1.8.3.js/src/ underscore-1.8.3.js#l519-l547

JS Array de-weight method

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.