Home > Mobile >  how to compare 2 array for multiple select in javascript
how to compare 2 array for multiple select in javascript

Time:11-15

hi how to compare 2 array javascript for multiple select first array is account : ['ID': 2,'nama': 'test']['ID': 3,'nama': 'test1']['ID': 4,'nama': 'test4']['ID': 5,'nama': 'test5']

second array is account_selected : ['ID': 2,'nama': 'test']['ID': 5,'nama': 'test']

how to know on first array have id to second array, i have to code like this but just array [0] can compare

    $.each( account, function( i, value ) {
        var data = value;

        if (data.ID == account_selected[0].ID){
            temp  = '<option selected  value="' data.ID '" id="account_id' data.ID '" value="' data.ID '" >' data.nama '</option>'
        } else {
            temp  = '<option  value="' data.ID '" id="account_id' data.ID '" value="' data.ID '" >' data.nama '</option>'
        }
    });

this code just first compare first array account_selected ,i want to option is selected if data same

CodePudding user response:

You have to use nested array to match check the validation.

  var account = [
    {'ID': 2,'nama': 'test'},
    {'ID': 3,'nama': 'test1'},
    {'ID': 4,'nama': 'test4'},  
    {'ID': 5,'nama': 'test5'},
  ];
  var account_selected = [
    {'ID': 2,'nama': 'test'},
    {'ID': 5,'nama': 'test'}
  ];

  $.each( account, function( i, valueAccount ) {
    var dataAccount = valueAccount;

    $.each( account_selected , function( i, valueSelected ) {
      var dataSelected = valueSelected;
      var temp = '';
      if( (dataSelected.ID == dataAccount.ID) &&  (dataSelected.nama == dataAccount.nama) ){
      temp  = '<option selected  value="' dataSelected.ID '" id="account_id' dataAccount.ID '" value="' dataAccount.ID '" >' dataAccount.nama '</option>'
      }else{
      temp  = '<option  value="' dataAccount.ID '" id="account_id' dataAccount.ID '" value="' dataAccount.ID '" >' dataAccount.nama '</option>'
      }
      console.log(temp);
    });
  });
  • Related