search

Home  >  Q&A  >  body text

javascript - js数组中 删除重复对象 有什么快速的方法

var term_gpa = [ { year: '2013-2014', term: '1' },
{ year: '2013-2014', term: '1' },
{ year: '2013-2014', term: '1' },
{ year: '2013-2014', term: '1' },
{ year: '2013-2014', term: '1' },
{ year: '2013-2014', term: '1' },
{ year: '2013-2014', term: '1' },
{ year: '2013-2014', term: '1' },
{ year: '2013-2014', term: '1' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2013-2014', term: '2' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' },
{ year: '2014-2015', term: '1' } ]

比如上面那个要变成
var term_gpa = [{ year: '2013-2014', term: '1' },
{ year: '2013-2014', term: '2' },
{ year: '2014-2015', term: '1' } ]

巴扎黑巴扎黑2822 days ago342

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-10 15:12:05

    var unique = {};
    term_gpa.forEach(function(gpa){ unique[ JSON.stringify(gpa) ] = gpa });
    term_gpa = Object.keys(unique).map(function(u){return JSON.parse(u) }); 
    

    reply
    0
  • 黄舟

    黄舟2017-04-10 15:12:05

    最快的方法是利用字典,遍历一次你的数组,将year和term设为数组的键:
    var myArr = []; for(var item in term_gpa){ myArr[':'+item.year +':'+item.term] = item; };
    OK, myArr就是你要的去重的数组了。

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 15:12:05

    对象其实不能相互比较的,因为占据的内存不同。不过可以采用其他的方法来做,你看看我写的这个吧数组去重

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 15:12:05

    array.filter() 新增的数组方法

    reply
    0
  • Cancelreply