Home  >  Article  >  Web Front-end  >  Detailed explanation of js array deduplication and sorting

Detailed explanation of js array deduplication and sorting

小云云
小云云Original
2018-05-30 11:26:282657browse

This article mainly shares with you the detailed explanation of deduplication and sorting of js arrays. I hope it can help you.

1. Use indexOf to check whether it exists. If it does not exist, it is not added.

		var arr = ['aa','aa','aa','bb','bb',3,5,8,9,4,5,4];

		function unique(arr){
			var newArr = [];
			for(var i in arr){
				if(newArr.indexOf(arr[i]) === -1){
					newArr.push(arr[i])
				}
			}
			return newArr;
		}

2. Use filter to filter, and then use indexOf to check whether it exists.

		function unique1(arr){
			function aa(item, index, array){
				return array.indexOf(item) === index;  // 当前值在原数组中第一次出现的位置 === 他的索引,就证明它不是重复的,然后就返回去
			}
			var res = arr.filter(aa);
			return res
		}

Sort

		var conf = {
			compare : function(property){
				return function(a,b){
			        var value1 = a[property];
			        var value2 = b[property];
			        return value1 - value2;
			    }
			},
			sortList:function(arr,str){//数组排序
				if(Object.prototype.toString.call(arr).slice(8,-1) ==='Array'){
					if(str){
						var returnArr = arr.sort(this.compare(str));
					}else{
						var returnArr = arr.sort(this.sort(str));
					}
					
					return returnArr;
				}else{
					return arr;
				}
			},
			sort:function(arr){//数组排序
				if(Object.prototype.toString.call(arr).slice(8,-1) ==='Array'){
					var array = [];
					for(var i in arr){
						array.push(arr[i]);
					}
					for (var i = 1; i < array.length; i++) {
						var key = array[i];
						var j = i - 1;
							while (j >= 0 && array[j] > key) {
							array[j + 1] = array[j];
							j--;
						}
						array[j + 1] = key;
					}
					return array;
				}else{
					return arr;
				}
			}
		}
		

		var arr = [{a:2,b:&#39;x2&#39;},{a:3,b:&#39;x3&#39;},{a:1,b:&#39;x1&#39;}];
		var arr2 = [4,1,3,5,2]

		var newArr = conf.sortList(arr,&#39;a&#39;);
		var v = conf.sortList(arr2);
		console.log(newArr)
		console.log(v)

Related recommendations:

Detailed examples of several ideas for deduplication of JavaScript arrays

Sharing of several methods for deduplication of JavaScript arrays

PHP method code to implement array deduplication

The above is the detailed content of Detailed explanation of js array deduplication and sorting. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn