Sort 2 arrays with different sizes in jQuery

Asked

Viewed 36 times

1

I have the following problem, in my scenario I am capturing the Ids of a checkbox, I have a list of JSON objects where I need to compare these Ids with the Ids from the list of JSON objects. The problem is that they have different sizes.

My Code

var obj = [
                    { "Id": 1, "Nome": "José" },
                    { "Id": 2, "Nome": "João"},
            { "Id": 3, "Nome": "Maria"}
            ];

var ids = [1, 2];

var j = 0;

var usuarios = [];

for(var i = 0; i < obj.lenght; i++){

  j++;

    if(obj[i].Id == ids[j]){

    usuarios.push(obj[i]);

  }

}

console.log(usuarios);

1 answer

1


You should go through the array ids[] and check if in JSON there is occurrence where the key Id has the value of each item in the array. You can use the method .filter() and check the data:

var obj = [
{ "Id": 1, "Nome": "José" },
{ "Id": 2, "Nome": "João"},
{ "Id": 3, "Nome": "Maria"}
];

var ids = [1, 2, 4];

var usuarios = [];

for(var i = 0; i < ids.length; i++){

   obj.filter(function(a){
      if(a.Id == ids[i]){
         usuarios.push(a);
      }
   });

}

console.log(usuarios);

Another way is to do the opposite using .indexOf(), without iterating the array with for:

var obj = [
{ "Id": 1, "Nome": "José" },
{ "Id": 2, "Nome": "João"},
{ "Id": 3, "Nome": "Maria"}
];

var ids = [1, 3, 4];

var j = 0;

var usuarios = [];

obj.filter(function(a){
   verifica se o valor da chave Id existe na array
   if(~ids.indexOf(a.Id)){
      usuarios.push(a);
   }
});

console.log(usuarios);

  • Vlw, you helped a lot.

  • Blz... I added a second solution that I found even better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.