1. 双层循环

  1. const unique = array => {
  2. const res = [];
  3. for (let i = 0; i < array.length; i++) {
  4. const arrValue = array[i];
  5. for (var j = 0; j < res.length; j++) {
  6. const resValue = res[j];
  7. if (arrValue === resValue) {
  8. break;
  9. }
  10. }
  11. if (j === res.length) {
  12. res.push(arrValue)
  13. }
  14. }
  15. return res;
  16. }

2.indexOf

  1. const unique = array => {
  2. const res = [];
  3. for (let i = 0, len = array.length; i < len; i++) {
  4. const current = array[i];
  5. if (res.indexOf(current) === -1) {
  6. res.push(current)
  7. }
  8. }
  9. return res;
  10. }

3.filter

  1. const unique = array => array.filter((item, index, array) => array.indexOf(item) === index)

4.Object健值对

  1. const unique = array => {
  2. const obj = {};
  3. return array.filter(function(item, index, array){
  4. return obj.hasOwnProperty(typeof item + JSON.stringify(item))
  5. ? false
  6. : (obj[typeof item + JSON.stringify(item)] = true)
  7. })
  8. }
  9. const array = [{value: 1}, {value: 1}, {value: 2}, 2, 1, "1", "2", null, null, undefined, undefined, NaN, NaN];
  10. // [ { value: 1 }, { value: 2 }, 2, 1, '1', '2', null, undefined, NaN ]
  11. console.log(unique(array));

5.Set

  1. const unique = array => [...new Set(array)];

6.Map

  1. const unique = array => {
  2. const map = new Map();
  3. return array.filter(a => !map.has(a) && map.set(a, 1));
  4. };