0

I'm filtering a an array in Jquery depending of some button selections of the user. I loop over the possibilities and build a "result" array extending it with a "original_array" slice.

result = []
$.each(university_selection, function(index, value) {
     if ($(value).attr('name') == 'on') {
          partial = jQuery.grep(original_array, function(n) { return ( n.institucion == $(value).text()); });
          result = $.extend( result , partial )
     };
});

The filterign works fine, but the "extend" command seems to replace previous instance instead of "accumulating". I only get the last slice returned.

I guess it has something to do with the moment in which the "result = $.extend( result , partial )" is stored in memory.

Any clues?

2 Answers 2

1

To tweak your jQuery, you can push each item in partial to result:

result.push(...partial);

or

result = result.concat(partial)

But the overall code is kinda verbose, not very functional, and more computationally complex than it needs to be.

To reduce the computational complexity from O(n^2) to O(n), construct a Set of the on values, then .filter the original_array by whether the institucion property is included. The logic will probably be a lot clearer to follow as well:

const selectedValues = new Set(
  [...university_selection]
    .filter(elm => elm.name === 'on')
    .map(elm => elm.textContent)
);
const result = original_array.filter(item => selectedValues.has(item.institucion));

This way, you only iterate over the original_array once, and a plain .filter constructs the result array based on a simple condition.

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

Comments

0

I could resolve the issue using

result = result.concat( partial );

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.