How to get only unique items in a multidimensional array with JavaScript/jquery?

核能气质少年 提交于 2019-12-11 15:21:49

问题


I got for example a multidimensional array items with 2 dimensions. I get this array from a database, but it will fill up to 2600+ objects, but if i could some how unique this it would be around 30 objects. How to solve this?

The set up is: How i get the information:

$.getJSON(url1,function(data1)
{
    for (var i in data1.layers){
        $.each(data1.layers[i].legend, function( a, b ) {
            for(var a in data1.layers[i].legend[a]){
                $.each(data1.layers[i].legend, function( key, val ){
                    items.push({label: val.label, url: "long link" + val.url});
                });
            };
        });     
    };

items[0].label  
items[0].url 
items[1].label    
items[1].url

etc...

I found another stackoverflow page about this in php, but i can't get it to work in JavaScript/JQuery. Stackoverflow php solution


回答1:


Use a dictionary to see which item you have already:

var dict = {};

$.getJSON(url1,addToLocalArray);

function addToLocalArray(data1){

  for (var i in data1.layers){

    $.each(data1.layers[i].legend, function( a, b ) {

        for(var a in data1.layers[i].legend[a]){

            $.each(data1.layers[i].legend, function( key, val ){

              if(!dict[val.url+'-'+val.label]){
                // or create some sort of unique hash for each element...
                dict[val.url+'-'+val.label] = 1;

                items.push({label: val.label, url: "long link" + val.url});
              }

            });

        }
    });
  }
}



回答2:


You're making a mistake in pushing them onto an array in the first place. You should be creating an associative array, with the key field the unique aspect.




回答3:


I would suggest either:

A)Push the Uniqueness filtering logic off to the database. It's much more efficient at this, and won't require exhaustive iteration.

B)Have a key for each unique Item (As vogomatix suggested).



来源:https://stackoverflow.com/questions/20355058/how-to-get-only-unique-items-in-a-multidimensional-array-with-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!