-3

How can I group items inside of a loop using jQuery?

I have these items like these in each loop iteration:

['ab', 'sd']
['ab', 'dc']
['ab', 'ca']
['bc', 'ds']
['bc', 'ea']

And I need to have an output like this:

{'ab':[sd,dc,ca],'bc':[ds,ea]}

I tried to filter them, but I couldn't achieve this.

4
  • stackoverflow.com/questions/14427659/jquery-array-group-by Commented Dec 16, 2022 at 12:49
  • This is not list that exact things this is loop array each array inside loop that loop how to make group ['ab', 'sd'], ['ab', 'dc'],['ab', 'ca'], ['bc', 'ds'], ['bc', 'ea'], ['bc','ea',ta] output {'ab':[sd,dc,ca],'bc':[ds]{'ea',[ta]} like this Commented Dec 16, 2022 at 13:02
  • Does this answer your question? jquery array group by Commented Dec 19, 2022 at 18:37
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Dec 19, 2022 at 21:36

1 Answer 1

0

1 way you can do it is like this:

$.each(input, function(i, n) {
  var keyW = n[0];
  if (output[keyW] == undefined) {
    output[keyW] = [];
  }

  if ($.inArray(n[1], output[keyW]) === -1) {
    output[keyW].push(n[1])
  }

})

Demo

var input = [
  ['ab', 'sd'],
  ['ab', 'dc'],
  ['ab', 'ca'],
  ['bc', 'ds'],
  ['bc', 'ea'],
  ['bc', 'ea']
];


var output = {};


$.each(input, function(i, n) {
  var keyW = n[0];
  if (output[keyW] == undefined) {
    output[keyW] = [];
  }

  if ($.inArray(n[1], output[keyW]) === -1) {
    output[keyW].push(n[1])
  }

})


console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

This is works only two array only what about third one when ever if third value also is same then create inner child array example : ['VSB', 'Agent'] ['VSB', 'Agent Procedure'] ['VSB', 'Anti-Malware'] ['TraverseOut', 'Devices'] ['TraverseOut', 'Signatures'] ['BS', 'HR'] ['BS', 'Finance'] ['AnuuthAnvil', 'On-Demand', '2FA'] ['AuthAnvil', 'On-Premise', '2fa'] ['Unigma', 'Monitor'] ['Unigma', 'Report'] ['365 Command', 'Monitor'] ['365 Command', 'Report']
@Methababu 3 array was not part of your original question.

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.