Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery match values of single array and object and redefined object

I have two arrays

array_1 & array_2 . Here I want to get the values of array_2 that matches values of array_1. Please see my code below

<script>
$(document).ready(function(){
    var array_1 = ['58', '10'];
    var array_2 = {};
    array_2 [0]=  {'id':55, 'name':'raj'};
    array_2 [1]=  {'id':58, 'name':'min'};
    array_2 [2]=  {'id':10, 'name':'max'};
    array_2 [3]=  {'id':12, 'name':'res'};
    
    var size = Object.keys(array_2).length;
    for (z=0; z<size; z++) {
        
        if((array_1[z] !== undefined && array_1[z] !=='') && array_2[z].id == array_1[z]) {
            console.log(array_2[z].id)
        }
    }

});
</script>

here I need to get array_2 as

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array_2[0] = {'id':58, 'name':'min'};
array_2[1] = {'id':10, 'name':'max'};

ie

array_2 = [0=>{'id':58, 'name':'min'}, 1=> {'id':10, 'name':'max'}] ;

Please help to solve this issue

>Solution :

You can do something like this:

// Initialize an empty object to store the reordered version of array_2
var newArray = {};

// Iterate through each element in array_1
for (var i = 0; i < array_1.length; i++) {
  // Iterate through each element in array_2
  for (var j = 0; j < Object.keys(array_2).length; j++) {
    // Check if the id of the current element in array_2 matches the current element in array_1
    if (array_2[j].id == array_1[i]) {
      // If a match is found, add the element from array_2 to the newArray object with the index from array_1 as the key
      newArray[i] = array_2[j];
    }
  }
}

Demo

var array_1 = ['58', '10'];
var array_2 = {};
array_2[0] = {
  'id': 55,
  'name': 'raj'
};
array_2[1] = {
  'id': 58,
  'name': 'min'
};
array_2[2] = {
  'id': 10,
  'name': 'max'
};
array_2[3] = {
  'id': 12,
  'name': 'res'
};

var newArray = {};
for (var i = 0; i < array_1.length; i++) {
  for (var j = 0; j < Object.keys(array_2).length; j++) {
    if (array_2[j].id == array_1[i]) {
      newArray[i] = array_2[j];
    }
  }
}
console.log(newArray);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading