0

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

5
  • account_selected[0] should be account_selected[index] Commented Nov 13, 2021 at 11:31
  • error bro Uncaught TypeError: Cannot read properties of undefined (reading 'ID') Commented Nov 13, 2021 at 11:36
  • That means there is no match. You should also check (first) that index > -1. So if (index > -1 && data.ID == account_selected[index].ID). Why do you use jQuery functions for this? Native JavaScript has functions for this... Use jQuery for DOM manipulation, but not for working with or looping over arrays. Commented Nov 13, 2021 at 11:41
  • can you explain in jsfiddle? Commented Nov 13, 2021 at 11:49
  • The Array structure you provided seems to be invalid, Also the explanation could be better. Commented Nov 13, 2021 at 12:13

1 Answer 1

1

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);
    });
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.