配列の重さを取り除く方法(未完)

2054 ワード

配列除去1-indexof
var arr = [32, 44, 88, 1, 58, 116, 17, 1, 116, 58, 19, 116];
        console.log(arr);
        function fn(arr) {
            arr.sort(function(a,b){
                return a-b;
            });
            var tempArr=[arr[0]];
            for (var i = 1; i < arr.length; i++) {
                if(arr[i] !== arr[i-1]){
                    tempArr.push(arr[i]); 
                }
            }
            return tempArr;
        }
        console.log(fn(arr));
配列除去重さ2-sort
var arr = [32, 44, 88, 1, 58, 116, 17, 1, 116, 58, 19, 116];
        console.log(arr);
        function fn(arr) {
            var tempArr = [];
            for (var i = 0; i < arr.length; i++) {
                if (tempArr.indexOf(arr[i]) == -1) {
                    tempArr.push(arr[i]);
                }
            }
            return tempArr;
        }
        console.log(fn(arr));
配列除去3-splice
var arr = [32, 44, 88, 1, 58, 116, 17, 1, 116, 58, 19, 116];
        console.log(arr);
        function fn(arr) {
            for (var i = 0; i < arr.length; i++) {
                for (j = i + 1; j < arr.length; j++) {
                    if (arr[i] === arr[j]) {
                        arr.splice(j, 1);
                    }
                }
            }
            return arr;
        }
        console.log(fn(arr));
配列デ重量4-オブジェクトの使用
 var arr = [32, 44, 88, 1, 58, 116, 17, 1, 116, 58, 19, 116];
 console.log(arr);

function fn(arr) {
            var obj = {};
            for (var i = 0; i < arr.length; i++) {
                if(obj[arr[i]]){
                    obj[arr[i]]++;
                } else {
                    obj[arr[i]] =1;
                }
            }
            debugger;
            var tempArr=[];
            for(var key in obj){
                tempArr.push(key);
            }
            return tempArr;
        }
        console.log(fn(arr));
ES 6のセットを使う
[...new Set([1,2,3,3,4,5,5])]   //