首页 > 试题广场 >

编写一个Javascript函数,传入一个数组,对数组中的元

[问答题]
编写一个Javascript函数,传入一个数组,对数组中的元素进行去重并返回一个无重复元素的数组,数组的元素可以是数字、字符串、数组和对象。举例说明:
    1. 如传入的数组元素为[123, "meili", "123", "mogu", 123],则输出:[123, "meili", "123", "mogu"]
    2. 如传入的数组元素为[123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"],则输出:[123, [1, 2, 3], [1, "2", 3], "meili"]
    3. 如传入的数组元素为[123, {a: 1}, {a: {b: 1}}, {a: "1"}, {a: {b: 1}}, "meili"],则输出:[123, {a: 1}, {a: {b: 1}}, {a: "1"}, "meili"]
function removeDuplicate(arr) {
  return[...(newSet(arr.map(n => JSON.stringify(n))))].map(n => JSON.parse(n))
}
发表于 2019-04-04 22:58:00 回复(1)
Array.prototype.unique = function(){
let hash = new Map()
let result = []
let item
for (let i = 0; i < this.length; i++) {
console.log(Object.prototype.toString.call(this[i]))
if (Object.prototype.toString.call(this[i]) === '[object Object]'
|| Object.prototype.toString.call(this[i]) === '[object Array]') {
item = JSON.stringify(this[i])
} else {
item = this[i]
}
if (!hash.has(item)) {
hash.set(item, true)
result.push(this[i])
}
}
return result
}
发表于 2019-04-04 11:06:14 回复(4)
function delRepeat(arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
if (i === 0) {
result.push(arr[i]);
} else if (isAdd(result, arr[i])){
result.push(arr[i])
}
}
return result;
}
function isAdd(result, val) {
for (let value of result) {
if (isEqual(value, val)) return false;
}
return true;
}
function isEqual(val1, val2) {
let type1 = typeof val1;
let type2 = typeof val2;
if (type1 !== type2) return false;
if (type1 !== 'object') return val1 === val2;
for (let key of Object.keys(val1)) {
if (!val2[key]) return false;
if(!isEqual(val1[key], val2[key])) return false;
}
return true;
}

发表于 2019-04-02 16:35:10 回复(0)
function resetRepeat(array) {
   var noRepeat = []
   noRepeat = Array.from(new Set(array))
   return noRepeat
}

function resetRepeat2(array) {
   var noRepeat = []
   for(var i = 0; i < array.length; i++) {
      if (noRepeat.indexOf(array[i] < 0) {
         noRepeat.push(array[i])
      }
   }
   return noRepeat 
}

function resetRepeat3(array) {
   var noRepeat = []
   var Obj = 
   for(var i = 0;i < array.length; i++) {
     Obj[array[i]]= array[i]
   }
   noRepeat = Object.keys(Obj)
   return noRepeat 
}

发表于 2019-03-28 10:30:46 回复(1)
function(arr){
 return [...new Set(arr)]
}
发表于 2019-03-29 06:29:17 回复(9)

function unique(arr){
    return Array.from(new Set(arr));
}
发表于 2019-04-15 23:15:52 回复(0)
借鉴@gradient的思路,es5实现:
```
function unique(arr){
var arr2 = [];
var arr3 = [];
var flag = true;
var item;
for (var i = 0; i < arr.length; i++) {
if(typeof(arr[i]) == "object"){
item = JSON.stringify(arr[i]);
}else{
item = arr[i];
}
if(arr3.indexOf(item) == -1){
arr3.push(item);
//考虑NaN
if(arr[i] !== arr[i] && flag){
arr2.push(arr[i]);
flag = false;
}
if(arr[i] === arr[i]){
arr2.push(arr[i]);
}
}
}
return arr2;
}
```
编辑于 2019-04-05 16:47:27 回复(0)
function getArr(arr) {
    return [...new set(arr)]
}

function getArr(arr) {
    var retArr = []
    var map = {}
    for (var i = 0; i < arr.length; i++) {
        if (!map[arr[i]]) {
            map[arr[i]] = 1
            retArr.push(arr[i])
        }
    }
    return retArr
}
发表于 2020-02-11 17:18:17 回复(0)
委屈恶气
发表于 2019-09-27 16:10:32 回复(0)
function delrep(list){
  let newlist=[];
  let item;
  let strlist=[];
  for(let i=0;i<list.length;i++){
     if(typeof(list[i])==='object'){
       item=JSON.stringify(list[i]);
       if(strlist.indexOf(item)===-1){
         strlist.push(item);
         newlist.push(JSON.parse(item));
       }
     }
     else{
       item=list[i];
       if(newlist.indexOf(item)===-1){
          newlist.push(item);
       }
     }
  }
  return newlist;
}
发表于 2019-08-27 15:49:36 回复(0)
1.使用ES6中的Map数据结构,将数组中的每一个值作为key,如果map实例中没有存储该key值(使用map.has(key)),则存入(使用
map.set(key,value)),并将其value设置为该元素在数组中的索引值(index),继续遍历,如果有相同的值,则将数组中的该值去除掉。
注意:因为数组元素中存在相同的对象或者数组,所以需要利用JSON.stringify()将每一个元素转换为JSON字符串。

let reaptArr = (arr) => {
    let map = new Map();
    arr.forEach((ele, index) => {
        if (map.has(JSON.stringify(ele))) {
            arr.splice(index, 1);
        } else {
            map.set(JSON.stringify(ele), index);
        }
    });
    return arr;
}

发表于 2019-08-08 10:09:26 回复(0)
function ded(arr) {
var temp={};
var len=arr.length;
var result=[];

for(var i=0;i<len;i++) {
if(typeof arr[i]==='object') {
arr[i]=JSON.stringify(arr[i]);
}
if(typeof arr[i]==='function') {
arr[i]=arr[i].toString().replace(/\s/g,'');
}

if(!temp[arr[i]]) {
result.push(arr[i]);
temp[arr[i]]=true;
}
}

return result;
}
发表于 2019-07-07 12:00:45 回复(0)
function remove(arr){
return newArr = [...new Set(arr)]
}

发表于 2019-06-24 17:04:50 回复(0)
function noRepeat(array){
var tempArray=[]
for(var i=0;i<array.length;i++){
var element= array[i]
var json=JSON.stringify(element)
var isRepeat=false
for(var j=0;j<tempArray.length;j++){
if(tempArray[j]===json){
isRepeat=true
}
}
if(!isRepeat){
tempArray.push(json)
}
}
for(var k=0;k<tempArray.length;k++){
tempArray[k]=JSON.parse(tempArray[k])
}
return tempArray
}
发表于 2019-05-12 22:32:51 回复(0)
function array_delete(arr) {  var item  var result = [] // 对数组中的对象进行转换  for(var i = 0; i < arr.length; i++){ if(Object.prototype.toString.call(arr[i]) === '[object Object]'  || Object.prototype.toString.call(arr[i]) === '[object Array]') { item = JSON.stringify(arr[i])
        }else{ item = arr[i]
        } result.push(item)
    } for(var i = 0; i < result.length; i++){ for(var j = i+1; j < result.length; j++){ if(result[i] == result[j]) result.splice(j, 1)
        }
    } return result  }

发表于 2019-04-11 17:30:21 回复(0)
//思路:利用深层递归比较,然后利用选择排序的思想取出当前需要被删除的元素,再一次性删除 function quChong(arr) {
function quChong(arr) {
let delArr = []; const isSame = function(obj1,obj2){ if(typeof obj1!=="object"){ return obj1===obj2 } // 属性长度是否相等 if(Object.keys(obj1).length!==Object.keys(obj2).length){ return false } // 对象 if(Object.prototype.toString.call(obj1).includes("Object")){ for(let i in obj1){ if(obj1[i]!==obj2[i]){ if(typeof obj1[i]!=="object" && typeof obj2[i]!=="object"){ return false }else{ if(!isSame(obj1[i],obj2[i])){ return false } } } } return true }else{ // 数组

return obj1.every((value,index)=>{ if(value!==obj2[index]){ if(typeof value!=="object" && typeof obj1[index]!=="object"){ return false }else{ if(!isSame(value,obj2[index])){ return false } } } return true }) } }; // 取出每一个相同的元素的索引

arr.forEach(((value,index,array) => { // 每一个item跟下面的value比较 let tempArr = array.slice(index+1); tempArr.forEach((value1,index1) => { // 相同就存在数组里 if(isSame(value,value1)){ if(index1+index+1===16){ console.log(value,value1); } delArr.push(index1+index+1); } }) })); // 索引数组去重降序,方便splice delArr = [...new Set(delArr)].sort((a,b)=>b-a); // console.log(delArr); // 删除 delArr.forEach((value => { arr.splice(value,1) })); return arr }


编辑于 2019-04-10 16:21:24 回复(0)

function remove(array) {
    var length = array.length;
    var result = [];
    for(let i = 0; i < length; i ++) {
        if(array[i] instanceof Array || array[i] instanceof Object) {             //若子项为数组或对象
            if(result.indexOf(JSON.stringify(array[i])) == -1) {                    //转化为字符串对象或字符串数组存入
                result.push(JSON.stringify(array[i]))
            }
        }else{
            if(result.indexOf(array[i]) == -1) {
                result.push(array[i])
            }
        }
    
    }

    for(let i = 0; i < result.length; i ++){
        if(typeof result[i] == "number") {

        }else if(result[i].indexOf(",") != -1){                                     //将字符串对象或数组转化为对象或数组
                result[i] = JSON.parse(result[i])
        }else if(result[i] == '{}'){
            result[i] = {}
        }
    
    }

    return result;
}
发表于 2019-04-10 14:28:29 回复(0)
function equal(a, b) {     if (typeof a !== typeof b) return false;     if (Array.isArray(a)) {         return a.every((item, index) => equal(item, b[index]));     } else if (typeof a === 'object') {         const akeys = Object.keys(a);         const bkeys = Object.keys(b);         return akeys.every((item, idx) => equal(a[item], b[item])) && bkeys.every((item, idx) => equal(a[item], b[item]));     } else {         return a === b;     }
}

function clear(arr) {     const arrs = [];     const objs = [];     const result = [...arr];          for (let i of arr) {         if (Array.isArray(i)) {             arrs.push(i);         } else if (typeof i === 'object') {             objs.push(i);         }     }     for (let i = result.length - 1; i >= 0; i--) {         const item = result[i];         if (Array.isArray(item)) {             arrs.pop();             if (arrs.some(x => equal(x, item))) {                 result.splice(i, 1);             }         } else if (typeof item === 'object') {             objs.pop();             if (objs.some(x => equal(x, item))) {                 result.splice(i, 1);             }         }     }     return [...new Set(result)];
}

发表于 2019-04-06 22:29:29 回复(0)

function unique(arr){
let itemIndex = new Map();
let resArr = [];
arr.forEach(item=>{
if(!itemIndex.has(item)){
resArr.push(item);
itemIndex.set(item,1)
}
})
return resArr;
   }
编辑于 2019-03-31 22:38:36 回复(0)

const distinct = arr => {

return Array.from(new Set(arr))

}


编辑于 2019-03-28 11:16:09 回复(0)