Javascript,从每个循环获取唯一值或按值分组

时间:2014-11-28 07:46:21

标签: jquery arrays regex foreach underscore.js

我将值存储在localStorage中,并在从localStorage检索它们后将它们转换为数组。

我只想返回唯一值或者可能将它们分组,因此没有重复项。我在循环中使用了_underscore。

$.get_played_songs = function(){
                if (localStorage.getItem("local_songs") === null) { 
                    recent_holder.html('Play some music');
                    } else {
                    var StoredPlays = JSON.parse(localStorage.getItem('local_songs'));  
                    var i=0
                    _.each(StoredPlays, function(value, key){
                        recent_holder.append("<div class='recently_played_jams' data-recently_played_sid='"+value.sid+"'>"+value.title+"</div>");
                    });
                } 
            }

控制台记录&#34;价值&#34;返回此。

Object { title: "Song1", sid: "47" }
Object { title: "Song1", sid: "47" } 
Object { title: "Song1", sid: "47" }
Object { title: "Song12", sid: "47" }
Object { title: "Song2", sid: "47" }
Object { title: "Song2", sid: "47" }
Object { title: "Song2", sid: "47" }

所以我想通过sid分组。也许是一些正则表达式。

1 个答案:

答案 0 :(得分:2)

_.uniq允许您传入一个函数,该函数确定在确定唯一性时要查看的内容,因此如果它是sid使其唯一:

StoredPlays = _.uniq(StoredPlays, function(play) { return play.sid; });

var StoredPlays = [
  { title: "Song1", sid: "47" },
  { title: "Song1", sid: "47" } ,
  { title: "Song1", sid: "47" },
  { title: "Song12", sid: "47" },
  { title: "Song2", sid: "47" },
  { title: "Song2", sid: "47" },
  { title: "Song2", sid: "47" }
];
StoredPlays = _.uniq(StoredPlays, function(play) { return play.sid; });
snippet.log(JSON.stringify(StoredPlays));
<script src="http://underscorejs.org/underscore.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

或者如果它是sid title

StoredPlays = _.uniq(StoredPlays, function(play) { return play.sid + "/" + play.title; });

var StoredPlays = [
  { title: "Song1", sid: "47" },
  { title: "Song1", sid: "47" } ,
  { title: "Song1", sid: "47" },
  { title: "Song12", sid: "47" },
  { title: "Song2", sid: "47" },
  { title: "Song2", sid: "47" },
  { title: "Song2", sid: "47" }
];
StoredPlays = _.uniq(StoredPlays, function(play) { return play.sid + "/" + play.title; });
snippet.log(JSON.stringify(StoredPlays));
<script src="http://underscorejs.org/underscore.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>