js array to reorder (ascending, descending, random) method

js native de-reordering

var hhl = [1, 5, 6, 3, 2, 7, 6, 1, 5, 4, 8, 6, 9]
        var newArr = [];//创建一个新数组
        var isRepeat = false;//判断
        for (var i in hhl) {
            isRepeat = false;
            for (var h in newArr) {
                if (newArr[h] == hhl[i]) {
                    isRepeat = true//如果数组的数值相等返回true
                }
            }
            if (!isRepeat) {
                newArr[newArr.length] = hhl[i]
                //不相等的数值放入新的数组
            }
        }
        console.log("去重后的", newArr)
  //冒泡排序
        var temp;
        for (var i = newArr.length; i > 0; i--) {
            for (var j = 0; j < i - 1; j++) {
                if (newArr[j] >newArr[j + 1]) {
                    //>升序 <降序

                    temp = newArr[j];
                    newArr[j] = newArr[j + 1];
                    newArr[j + 1] = temp;
                }
            }
        }
        console.log("去重排序后的", newArr)

Use for to nest for, and then splice to remove duplicates (most commonly used in ES5) 

Use ES6 Set to deduplicate (the most commonly used in ES6) recommendation (convenient) 

Note : 1. Because the Set data structure is not a real array, it is similar to an array, and its member values ​​are unique without duplication, so it can be used for deduplication. But because it is an array-like structure, it needs to be transformed into a real array to use. So you need to use Array.from

2. If it is not a string type, but the object will not be deduplicated: so you can use JSON.stringify to convert it into a string type, and then you can use new Set to deduplicate the array, and then use Array.from to convert it to real array.

Also available (JSON.parse conversion)

Use indexOf to deduplicate 

Use sort() to deduplicate 

 Use the characteristics that the attributes of the objects cannot be the same for deduplication

Use includes to deduplicate 

Use es6's set data structure in js to remove duplicate objects in array objects

  //去重
      const noRepeat = [
        ...new Set(this.datainfo.userList.map((item) => JSON.stringify(item)))
      ]
      this.datainfo.userList = noRepeat.map((item) => JSON.parse(item))

Array objects are deduplicated according to attribute values

    unique(arr) {
      var newArr = [];
      for (var i = 0; i < arr.length; i++) {
        if (!newArr.includes(arr[i])) {
          newArr.push(arr[i]);
        }
      }
      return newArr;
    },

for loop

let data = [
  {sum:1,data:'20200907'},
  {sum:5,data:'20200906'},
  {sum:8,data:'20200907'},
  {sum:12,data:'20200908'},
]

var arr1 = []
let obj = {}
for(var i = 0;i<data.length;i++){
  if (!obj[data[i].data]) {
    arr1.push(data[i]);
    obj[data[i].data] = true;
    }
}
console.log(arr1)

Es6

function filterArr(Arr,data){

let newarr={};
return Arr.reduce((vlaue,item)=>{

newarr[item[data]] ? '':newarr[item[data]]=true && vlaue.push(item);

return value;
},[]);


  let data = [
  {sum:1,data:'20200907'},
  {sum:5,data:'20200906'},
  {sum:8,data:'20200907'},
  {sum:12,data:'20200908'},
 ];
function filterArr(Arr, data) {
    let newarr = {};
     return Arr.reduce((ok, item) => {
        newarr[item[data]] ? '' : newarr[item[data]] = true && ok.push(item);
        return ok;
    }, []);
}
let Arr = filterArr(data, 'data');
console.log(Arr);

Note: If there are multi-dimensional arrays such as [1,[2],[3,[2,3,4,5]] ], first flatten and then remove duplication,
use Array.flat(Infinity) to achieve flattening.

Insertion sort:

   Ascending thought: It is generally assumed that the first element in the front is an ordered sequence. The elements behind the loop are compared with the last element in the previous ordered sequence. If the latter element is greater than the last element in the ordered sequence, there is no need to move the position. If the following element A is smaller than the last element of the ordered sequence, then A should continue to search to the front of the ordered sequence, find the location where it should be stored, and insert element A at this location.

​​  var numbers = [3, 44, 38, 5, 47, 15, 36, 26, 27];
        for(var i=0;i<numbers.length;i++){
            //取出后面一位的元素 和 前面的有序序列进行对比
            for(var j=i+1;j>0;j--){
                if(numbers[j]<numbers[j-1]){ //后面的元素比有序序列的前一个元素小,交换位置
                    //交换位置
                    var tmp=numbers[j];
                    numbers[j]=numbers[j-1];
                    numbers[j-1]=tmp;
                }else{
                    //如果当前元素没有比前面的小,这个元素在当前位置不动.它已经是有序队列里面最大.
                    break;
                }
            }
        }
        console.log("插入排序的结果==>",numbers);

       var nums = [3, 44, 38, 5, 47, 15, 36, 26, 27];
        //从1开始循环 假设第一个元素是一个有序列表
        for(var i=1;i<nums.length;i++){
            var preIndex=i-1;//代表 有序列表的最后一个元素的下标
            var current=nums[i];//取出当前的值.
            //判断 preIndex 下标大于0 当前值如果比有序列表的最后一个值要小
            while(preIndex>0 && current<nums[preIndex]){
                nums[preIndex+1]=nums[preIndex];//把前面比当前值大的数据往后挪一位
                preIndex--;//继续查找前面的元素 往后面挪.
            }
            //前面已经挪动完成,现在把当前值插入前面位置.
            // XXXXXXXXXXXX 条件不成立的时候 多减了1 所有这里加+1
            nums[preIndex+1]=current;
        }
        console.log("插入排序结果22==》",nums);

 Bubble Sort

 It is stipulated that the array is sorted from small to large, that is, in ascending order 

Idea: Starting from the first element, two adjacent elements are compared in pairs, and if the previous value is greater than the latter value, the positions are exchanged.

method one:

​​​​     var nums = [25,3,16,36,30,11,42,47,39,20];
        for(var i=0;i<nums.length;i++){
         
            for(var j=0;j<nums.length-i-1;j++){
                if(nums[j]>nums[j+1]){
                    //大于,小于==升序和降序
                    var tmp=nums[j];
                        nums[j]=nums[j+1];
                        nums[j+1]=tmp;
                }
            }
        }
        console.log('另外写法==>',nums);

Method Two:

  var numbers = [25,3,16,36,30,11,42,47,39,20];
        var temp;//临时变量
        for(var i=numbers.length;i>0;i--){
            //里面的循环每执行一次就会找到一个最大值
            // for(var j=0;j<numbers.length;j++) 循环100次.
            for(var j=0;j<i-1;j++){// 第一次 查找9次才能找到最大值 第二次只要循环8次就可以找到第二大值.
                if(numbers[j]>numbers[j+1]){//如果当前值比后一个值大就交换位置,把大的值往后面排.
                    //交换位置
                    temp=numbers[j];
                    numbers[j]=numbers[j+1];
                    numbers[j+1]=temp;
                }
            }
        }
        console.log(numbers);

Method three :

/降序而且用 while循环实现.
        var numbers2 = [25,3,16,36,30,11,42,47,39,20];
        var x=numbers2.length;
        while(x>0){
            var y=0;
            while(y<x-1){
                if(numbers2[y]<numbers2[y+1]){ //判断前一个元素比后一个小 交换位置
                    var t=numbers2[y];
                    numbers2[y]=numbers2[y+1];
                    numbers2[y+1]=t;
                }
                y++;
            }
            x--;
        }
        console.log("numbers2==>",numbers2)

Random sorting of arrays

method one:

   var arr =[1,2,3,4,5,6,7,8,9,10];
        function randSort1(arr){

            for(var i=0,len=arr.length;i<len;i++){
                var rand=parseInt(Math.random()*len);
                var temp=arr[rand];
                arr[rand]=arr[i];
                arr[i]=temp;
            }
            return arr;

        }
        console.log(randSort1(arr))

Method 2 (simple):

   var arr =[1,2,3,4,5,6,7,8,9,10];
        arr.sort(function(){
            return Math.random()-0.5;
        })
        console.log(arr)

Method three:


        var arr =[1,2,3,4,5,6,7,8,9,10];
        function randSort2(arr){
            var num=[];
            while(arr.length>0){
                var randoms=parseInt(Math.random()*arr.length);
                num.push(arr[randoms]);
                arr.splice(randoms,1);
            }
            return num;
        }
        console.log(randSort2(arr))

Guess you like

Origin blog.csdn.net/H_hl2021/article/details/121765275