haizlin / fe-interview

前端面试每日 3+1,以面试题来驱动学习,提倡每日学习与思考,每天进步一点!每天早上5点纯手工发布面试题(死磕自己,愉悦大家),6000+道前端面试题全面覆盖,HTML/CSS/JavaScript/Vue/React/Nodejs/TypeScript/ECMAScritpt/Webpack/Jquery/小程序/软技能……
http://www.h-camel.com
MIT License
25.43k stars 3.26k forks source link

[js] 第15天 写一个数组去重的方法(支持多维数组) #48

Open haizhilin2013 opened 5 years ago

haizhilin2013 commented 5 years ago

第15天 写一个数组去重的方法(支持多维数组)

linghucq1 commented 5 years ago
function flat(arr, target) {
  arr.forEach(item => {
    if (Array.isArray(item)) {
      flat(item, target)
    } else {
      target.push(item)
    }
  })
}

function flatArr(arr) {
  let result = []

  flat(arr, result)

  return result
}

function uniqueArr(arr) {
  return [...new Set(flatArr(arr))]
}

const result = uniqueArr([1, 2, 3, 4, [3, 4, [4, 6]]])

console.log(result) // 1,2,3,4,6

有一个兼容性不太好的写法:

function uniqueArr(arr) {
  return [...new Set(arr.flat(Infinity))]
}

参考:Array.prototype.flat

myprelude commented 5 years ago
think2011 commented 5 years ago

说个兼容性比较好的,当然最简单的方式还是基于 new Set

[1,2,3,4,4,5,5,2].filter((item, index, arr) => arr.indexOf(item) === index)
Damon99999 commented 5 years ago
// 将数组降维
function resetArray(arr, newArr){
    arr.forEach(item => {
        if (toString.call(item) === "[object Array]") {
        resetArray(item, newArr);
        } else {
        newArr.push(item);
    }
    })
}
// 将数组去重
function uniArr(arr) {
    var newArr = [];
    resetArray(arr, newArr);
    console.log([...new Set(newArr)]);
}
arr = [1, 2, 3, [1, 2, [3, 4]], [1]]
uniArr(arr);
AricZhu commented 5 years ago

/ 利用Set来去重 利用递归来处理多维情况 /

function getNoRepeatArr (arr, set) {

if (Array.isArray(arr)) {
    arr.forEach(item => getNoRepeatArr(item, set));
} else {
    set.add(arr);
}

}

Konata9 commented 5 years ago
// ES6
const uniqueArr = (arr) => [
  ...new Set(
    arr.reduce(
      (prev, cur) =>
        Array.isArray(cur) ? prev.concat(...uniqueArr(cur)) : prev.concat(cur),
      []
    )
  )
];

console.log(uniqueArr([1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1, 5, 6]));
console.log(uniqueArr([1, 2, 3, 4, 4, 3, 2, 1, [1, 2, 3, [4, 3, 2, 1]]]));
console.log(
  uniqueArr([
    1,
    2,
    3,
    [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3]]]]]]
  ])
);

// ES5
const uniqueArrES5 = (arr) => {
  const unique = [];
  const flattedArr = arr.reduce(
    (prev, cur) =>
      Array.isArray(cur)
        ? prev.concat(uniqueArrES5(cur))
        : prev.concat(cur),
    []
  );

  while (flattedArr.length > 0) {
    const head = flattedArr.shift();
    if (flattedArr.indexOf(head) < 0) {
      unique.push(head);
    }
  }
  return unique;
};

console.log(
  uniqueArrES5([1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1, 5, 6])
);
console.log(uniqueArrES5([1, 2, 3, 4, 4, 3, 2, 1, [1, 2, 3, [4, 3, 2, 1]]]));
console.log(
  uniqueArrES5([
    1,
    2,
    3,
    [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3]]]]]]
  ])
);
shufangyi commented 5 years ago
const flatArray = array =>
  array.reduce(
    (pre, item) =>
      Array.isArray(item) ? [...pre, ...flatArray(item)] : [...pre, item],
    []
  )

const uniqueArray = (array, fn = (a, b) => a === b) =>
  array.filter(
    (item, index) => array.findIndex(value => fn(value, item)) === index
  )

const test = [
  { name: '2' },
  { name: '1' },
  2,
  3,
  [4, 5, [6, 7, [8, { name: '2' }, 4, 9, [10, 9]]]]
]

console.log(uniqueArray(flatArray(test))) // [ { name: '2' }, { name: '1' }, 2, 3, 4, 5, 6, 7, 8, { name: '2' }, 9, 10 ]

console.log( // [ { name: '2' }, { name: '1' }, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 
  uniqueArray(flatArray(test), (a, b) => {
    return a === b || (a.name && b.name && a.name === b.name)
  })
)
wyx2014 commented 5 years ago
const multiLevel2OneLevel = function (arr) {
   const dedupliArr = arr.reduce(function (prev, cur) {
       return Array.isArray(cur)? prev.concat(multiLevel2OneLevel(cur)):prev.concat(cur);
   },[])
   return dedupliArr;
}
const deduplicatArr = function(arr) {
   return Array.from(new Set(arr));
}
const deduplicatArrTwo = function(arr) {
   const unique = [];
   while(arr.length > 0){
       var headVal = arr.shift();
       if(arr.indexOf(headVal) === -1) {
          unique.push(headVal);
      }
   }
   return unique;
}
console.log(deduplicatArr(multiLevel2OneLevel([11,233,45,11,[22,3,,233,45,[2,34,55,67,45]]])));
console.log(deduplicatArrTwo(multiLevel2OneLevel([11,233,45,11,[22,3,,233,45,[2,34,55,67,45]]])));
Vi-jay commented 5 years ago
function deWeighting(arr = []) {
  let targetIndex = null;
  arr = arr.slice();
  while ((targetIndex = arr.findIndex(Array.isArray)) > -1) {
    arr.splice(targetIndex, 1, ...arr[targetIndex].flat());
  }
  return [...new Set(arr)]
}
AchillesV commented 5 years ago
const uniqueArr = (arr) => {
  let result = []
  for (let i=0; i<arr.length; i++) {      
    arr[i] instanceof Array 
    ? result.push(removeArr(arr[i])) 
    : result.indexOf(arr[i]) === -1 ? result.push(arr[i]) : null;
  }
  return result
}
nnnnnnnnnni commented 5 years ago

function distinct(a){ return Array.from(new Set(a)) }

15190408121 commented 5 years ago

讲个比较笨的 var arrys = [] function arrs(arr) { // 先把所有的提出来 for (var i = 0; i < arr.length; i++) { if (Array.isArray(arr[i]) === true) { arrs(arr[i]) } else { arrys.push(arr[i]) } } } function Arrys(arr, arrys) { // 之后去重 arrs(arr) return [...new Set(arrys)] } Arrys([1, 2, 3, 4, 4, 3, 2, 1, [1, 2, 3, 5, [5, 4, 3, 2, 1]]], arrys)

wsypower commented 5 years ago
function deepFlatten(arr) {
  return [
    ...new Set(
      [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)))
    )
  ];
}
const result = deepFlatten([1, 2, 3, 4, [3, 4, [4, 6]]]);
console.log(result); // 1,2,3,4,6
Zhou-Bill commented 5 years ago
function dup(list) {
    let arr = flatten(list);
    let res = simple(arr);
    return res;
}
//先把他扁平化
function flatten(list) {
    const res = list.reduce((prev, current) => {
        let temp = current instanceof Array ? flatten(current) : current;
        return prev = prev.concat(temp);
    }, []);
    return res;
}

function simple(arr) {
    let res = new Set(arr);
    return [...res];
}
dup([1,2,3, [1,3,4]]);
fanqingyun commented 5 years ago

function rid(arr){ arr = arr.map(item=>{ if (item instanceof Array){ return rid(item) } else{ return item } }) return [...new Set(arr)] }

ZindexYG commented 5 years ago
function flat(arr, target) {
  arr.forEach(item => {
    if (Array.isArray(item)) {
      flat(item, target)
    } else {
      target.push(item)
    }
  })
  return target
}

function uniqueArr(arr) {
  let result = []
  let resultFilter = flat(arr, result)
  return [...new Set(resultFilter)]
}

// let resultArr = uniqueArr([1, 2, 3, 4, [3, 4, [4, 6]]])

// console.log(resultArr) // 1,2,3,4,6
Tseian commented 5 years ago
function unique(arr, index) {
    if (index == arr.length) return arr;
    let next = index + 1;
    if (Array.isArray(arr[index])) {
        arr[index] = unique(arr[index], 0);
        return unique(arr, next);
    } else {
        let hasSame = -1;
        for (let i = 0; i < index; i++) {
            if (arr[i] == arr[index]) {
                hasSame = i;
                break;
            }
        }
        if (hasSame > -1) { //删除
            arr.splice(hasSame, 1)
            return unique(arr, index);
        } else {
            return unique(arr, next);
        }
    }
}
const result = unique([1, 2, 2, 3, 4, [3, 3, 4, 4, [4, 6]]], 0)

console.log(result) // [ 1, 2, 3, 4, [ 3, 4, [ 4, 6 ] ] ]
diandianzd commented 5 years ago
const uniqueArr = (arr) => [...new Set(arr.toString().split(','))]

console.log(uniqueArr([1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1, 5, 6]));
console.log(uniqueArr([1, 2, 3, 4, 4, 3, 2, 1, [1, 2, 3, [4, 3, 2, 1]]]));
console.log(
  uniqueArr([
    1,
    2,
    3,
    [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3]]]]]]
  ])
);

// [ '1', '2', '3', '4', '5', '6' ]
// [ '1', '2', '3', '4' ]
// [ '1', '2', '3' ]
smeltH commented 5 years ago
function toSame(arr){
    const newArr = arr.toString().split(',');
    return [...new Set(newArr)];
}
0x3c commented 5 years ago
/**
 * 元素为非数组则直接对数组去重
 * 元素为数组则对元素去重
 * @param {array} arr
 * @return {array}
 */
function uniqueArr(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      arr[i] = uniqueArr(arr[i]);
    }
  }
  return Array.from(new Set(arr));
}
xiaobaichiliangpi commented 4 years ago
function flatAndUnique(target) {
    return [...new Set(target.join(',').split(','))]
}
const target = [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3, [1, 2, 3]]]]]]
flatAndUnique(target) // [1,2,3]
laixihong commented 4 years ago
let newArr = arr.toString().split();
Array.from(new Set(newArr))
YeChang commented 4 years ago
//第15天 写一个数组去重的方法(支持多维数组)

function flat(arr, result) {
  arr.map(item => {
    if (Array.isArray(item)) {
      flat(item, result);
    } else {
      result.push(item);
    }
  });
}

function flatArr(arr) {
  let result = [];

  flat(arr, result);

  return result;
}

function uniqueArr(arr) {
  return Array.from(new Set(flatArr(arr)));
}

var arr = [1, 2, [2, 3, [3, 4, 5]], 5, 5];

// console.log(uniqueArr(arr));
console.log(uniqueArr(arr));
YeChang commented 4 years ago
//另一个flat
function flat1(arr) {
  var result = [];
  arr
    .toString()
    .split(",")
    .map(item => {
      result.push(Number(item));
    });
  return result;
}

var arr = [1, 2, [2, 3, [3, 4, 5]], 5, 5];

// console.log(uniqueArr(arr));
console.log(flat1(arr));
kruzabc commented 4 years ago

1,首先是展平多维数组。 利用reduce+递归来展平多维数组。

 function flat(arr) {
     return arr.reduce(function (prev, curr) {
         return Array.isArray(curr) ? prev.concat(flat(curr)) : prev.concat(curr)
     },[]);
}

2.然后就是数组去重 数组去重就是可以用new Set的方式, 当然也有很多种其他方式。 合起来写就是

 function distinct(arr) {
    return [...new Set(flat(arr))]
}
susanforme commented 4 years ago

应该还有很大的改进空间

var ary=[1,1,2,2,3,['a','a','c',['q','q']]];
function bar(ary){
  for(let i=0;i<ary.length;i++){
    if(Array.isArray(ary[i])){
      bar(ary[i]);
    }else{
      for(let j=0;j<ary.length;j++){
        if(ary[i]===ary[j]&&i!=j){
          ary.splice(i,1);    
        }
      }
    } 
  }
}
276378532 commented 4 years ago
Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>a-b)
数组扁平化去重排序
rennzhang commented 4 years ago
function distinct(arr) {
  let result = [];
  let obj = {};
  for (let i of arr) {
    if (i instanceof Array) {
      result.push(distinct(i));
    } else if (!obj[i]) {
      result.push(i);
      obj[i] = 1;
    }
  }
  return result;
}
console.log(distinct(arr));
larry0442 commented 4 years ago

降维+去重

const flatten = (arr) => {
    const res = [ ];
    arr.forEach(item=>{
        Array.isArray(item) ? res.push.apply(res, flatten(item)) : res.push(item);
    })
   return res;
}
const distint = (arr) =>  {
    return [...new set(arr)]
}
qiqingfu commented 4 years ago
  const isArray = arr => Array.isArray(arr);

  const removeDuplicates = function (array) {
    if (!isArray(array)) {
      throw new Error('传递的不是数组')
    }
    return core(array);
  };

  function core(array) {
    if (!isArray(array)) {
      return array;
    }
    const noDups = [...new Set(array)];
    for (let i = 0; i < noDups.length; i++) {
      noDups[i] = core(noDups[i])
    }

    return noDups;
  }
shane-leon commented 4 years ago

var str=......; for(var i=0;i<str.length;i++){ for(var j=i+1;j<str.length;j++){ if(str[i]==str[j]){ str.splice(j,1); j--; } } }

blueRoach commented 4 years ago

降维:

function deduplication(arr, n){
    if(!arr instanceof Array){
        return
    }
    return [...new Set(arr.flat(n))]
}
13168335674 commented 4 years ago
const flatArr = (arr=[]) => {return [...new Set(arr.flat(Infinity))]};
giggleCYT commented 4 years ago
function fn(arr) {
            var newarr = new Set(arr.join(',').split(','));
            return [...newarr]

        }
Fengzhen8023 commented 4 years ago
function flattenArray(originArray) {
    let tempArr = [];
    for (let item of originArray) {
        if (Object.prototype.toString.call(item) === "[object Array]") {
            tempArr = [...tempArr, ...flattenArray(item)]
        } else {
            tempArr.push(item);
        }
    }
    return tempArr;
}

function removeDuplicatesFromArray(originArray) {
    if (Object.prototype.toString.call(originArray) !== "[object Array]") {
        return [originArray];
    }

    let flattenedArr = flattenArray(originArray);
    return [...new Set(flattenedArr)]
}

let arr = [
    1, 2, 3, 4, "Allen",
    { name: "Tom" },
    [2, 5, 6],
    [10, 5, [2, 6, 7]]
];

console.log(removeDuplicatesFromArray(arr));
laboonly commented 4 years ago

第15天 写一个数组去重的方法(支持多维数组)

arr = [1, 2, 3, [1, 2, [3, 4]], [1]]

//降维
function flatcopy(arr2) {
    var res = [];
    arr2.forEach(element => {
        if(Object.prototype.toString.call(element) == '[object Array]') {
            res = res.concat(flatcopy(element))
        } else {
            res.push(element)
        }
    });
    return res;
}

//去重
function uniq (arr) {
    var res = []

    arr.forEach(element => {
       if(res.indexOf(element) == -1) {
           res.push(element)
       }
    })
    return res;
}

//es6
//降维
let res = arr.flat(Infinity)

//去重

let res2 = new Set(res)

console.log([...res2])
console.log(uniq(flatcopy(arr)))
NongFuqi commented 4 years ago

var arr = [1, 2, 3, 4, [3, 4, [4, 6]]] function uniqueArr(arr) { return [...new Set(JSON.stringify(arr).match(/\d+/g))] } uniqueArr(arr)

zebratt commented 3 years ago

function unique(arr) {
  if (Array.prototype.flat !== undefined) {
    return [...new Set(arr.flat(Infinity))]
  }

  const set = new Set(arr);
  const res = [];

  for (const ele of set.values()) {
    res.push(Array.isArray(ele) ? unique(ele) : ele)
  }

  return res;
}
xiezhenghua123 commented 3 years ago

function outRepeat(arr) { return [...new Set(arr.flat(Infinity))] }

378406712 commented 3 years ago

const arr = [1, 2, 3, [1, 2, 3, [1, 2]]] let index = 0 function judgeFlat(arr) { index++ arr.map((item) => { Object.prototype.toString.call(item) === '[object Array]' ? removeSame(item) : '' }) } function removeSame(arr) { judgeFlat(arr) let newArr = arr.flat(index - 1) return [...new Set(newArr)] } console.log(removeSame(arr))

InkSha commented 3 years ago
let arrays = [1,2,3,[4,5,[6,7,[8,9],1,2],3,4],5,6,[7,8],9,[0]]
let ObjType = obj => Object.prototype.toString.call(obj).replace(/\[object\s|\]/g, '');// 判断类型
function ArrayGetBack(array = null, obj = []) { // 设置默认值
    if (ObjType(array) != 'Array') return TypeError(`错误:\n\t参数:${array} 不是一个数组`)// 如果 参数 array 的 类型 不等于 数组 返回一个 类型错误
    array.forEach(items => {// 遍历传入的 array  forEach 是对数组每一个元素执行一次函数 无法被终止 除非抛出异常
        if (ObjType(items) == 'Array') ArrayGetBack(items, obj)// 如果 遍历获得的 items 类型等于一个 数组 进行迭代
        else {// 如果不是一个数组
            for (let i of obj) if (i == items) return // for of 遍历 可以被终止
            obj.push(items) // 在 参数 obj 的 后面添加 items
        }
    })
    return obj // 返回 obj
}
console.log(ArrayGetBack(arrays))
codeyourwayup commented 3 years ago

先把数组拍平

const a=[1, 2, 3, 4, [3, 4, [4, 6]]];
const re=[];
function isFlat(arr){
  let flat=true;
  for(let a of arr){
    if(Array.isArray(a)){
     flat=false;
    }
  }
  return flat;
}
function flat(arr){
//if this array is flat, just push it
if(isFlat(arr)){
  re.push(...arr);
  return;
}
//if not flat, check each ele, if flat push, else recursive
for(let a of arr){
  if( !Array.isArray(a)){
   re.push(a);
  }else{
   flat(a);    
  }
}
}
//start 
flat(a);
console.log(re)
HNHED commented 3 years ago
amikly commented 2 years ago

ES5

//ES5
function uniqueArr(arr) {
    const result = [];
    const dimenArr = arr.reduce(
        (prev, curr) =>
        Array.isArray(curr) ? prev.concat(uniqueArr(curr)) : prev.concat(curr),
        []
    );
    while (dimenArr.length) {
        let element = dimenArr.shift();
        if (!dimenArr.includes(element)) {
            result.push(element);
        }
    }
    return result;
}
console.log(uniqueArr([1, 2, 3, 4, [3, 4, [4, 6]]]));

ES6

// ES6
function uniqueArr(arr) {
    [
        new Set(
            arr.reduce(
                (prev, curr) =>
                Array.isArray(cur)
                ? prev.concat(...uniqueArr(curr))
                : prev.concat(cur),
                []
            )
        ),
    ];
}
console.log(uniqueArr([1, 2, 3, 4, [3, 4, [4, 6]]]));
github-cxtan commented 2 years ago

function MyTypeof(data) { let str = Object.prototype.toString.call(data); return str.slice('[object '.length, str.length - 1); } var TestArray = [[1,2,2],[1,2,2]]; function UniqueArrar(array){ let DstArray = []; for (let index = 0; index < array.length; index++) { const element = array[index]; if (MyTypeof(element) === 'Array'){ let arr = []; for (let index = 0; index < element.length; index++) { const e = element[index]; if (arr.indexOf(e) === -1){ arr.push(e); } } DstArray.push(arr); }else { if (DstArray.indexOf(element) === -1){ DstArray.push(element); } } } return DstArray; }

yxllovewq commented 2 years ago
const arr2set = (arr = []) => {
  let newArr = [];
  for (let value of arr) {
    if (typeof value === 'number') {
      if (newArr.every(v => v !== value)) newArr.push(value);
    }
    else newArr.push(arr2set(value));
  }
  return newArr;
}
storm-cao commented 2 years ago
            const list = [];
    const arrayHandle = (array) => {
        array.map(item => {
            if (Array.isArray(item)) {
                arrayHandle(item);
            } else {
                list.push(item)
            }
        })

        return [...new Set(list)];
    }
wind8866 commented 2 years ago

看别人的结果都是一维数组,我这个去重并且保留原数组的格式(空数组去除)

const unique = (arr) => {
  const set = new Set()
  const loop = (arr) => {
    return arr.reduce((result, current) => {
      if (Array.isArray(current)) {
        const arrTemp = loop(current)
        if (arrTemp.length > 0) result.push(arrTemp)
        return result
      }
      if (set.has(current)) return result
      set.add(current)
      result.push(current)
      return result
    }, [])
  }
  return loop(arr)
}
unique([1,2,3,[1, 4, [2]],4,5], 7, 8, 7)
vesere commented 2 years ago

var arr = [ [11,1,2,2], [3,4,5,5], [6,7,8,9,10, [11,12, [12,12, [13] ] ] ] ]

// 1、数组扁平化 // 2、去重 // 3、排序

// 方法一:递归 要使用function因为this指向 不然箭头函数指向window Array.prototype.flat = function(){ // 首先将数组遍历处理 const result = this.map(item => { if(Array.isArray(item)) { console.log(item); console.log('-----------------------------------------------------------------------------------'); return item.flat() } return [item] }); return [].concat(...result) } console.log('-----------------------------------------------------------------------------------'); console.log(arr.flat());

const arr1 = [ 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 12, 13 ] const newArr = new Set(arr1) console.log(newArr); // 是一个对象类型所以需要将其转化为数组类型 console.log(typeof(newArr)); console.log(newArr.has(9)); console.log([...newArr]);

// 去重操作 Array.prototype.uniquee = function(){ return [...new Set(this)]
}

// 定义排序的顺序 const sortfn = (a,b)=>{ return a - b }

console.log('------------------------------------------------------------------------------------------------');

const newArray = arr.flat().uniquee().sort(sortfn)

console.log(newArray);

xiaoqiangz commented 2 years ago

// 写一个数组去重的方法 支持多维数组 var arr = [1, 2, [2, 3, [3, 4, 5]], 5, 5]; // 1, 升序且去重 console.log(Array.from(new Set(arr.flat(Infinity))).sort((a,b) => a - b)) // 2. reduce function flat(arr) { return arr.reduce((prev, cur) => { return Array.isArray(cur) ? prev.concat(flat(cur)) : prev.concat(cur) }, []) } console.log(Array.from(new Set(flat(arr)))) // 3 递归 function flatArr(arr, result) { arr.forEach(item => { if (Array.isArray(item)) { flatArr(item, result) } else { result.push(item) } }) return result } console.log([...new Set(flatArr(arr, []))])