Arrays provide the foundation for managing data in JavaScript. And jQuery gives us shorthand methods for easily manipulating array contents. In this guide, we‘ll explore the array landscape and see two fundamental techniques for removing values: splice() and grep().

Arrays in JavaScript

An array represents an ordered collection of values accessed by index. Let‘s create one:

let fruits = [‘apple‘, ‘banana‘, ‘orange‘];
fruits[0]; // ‘apple‘

The [] syntax defines a new array with three initial string elements. We can access those values via indexes, starting from 0.

This structure enables efficient storage, search, and manipulation. Under the hood, arrays are objects with special behavior including:

  • Setting length property to match highest integer index + 1
  • Unsigned 32-bit integer indexes allowing sparse arrays
  • Exposing handy methods like push and pop

Let‘s showcase some essential array capabilities:

Adding Elements

We can append new items with push():

fruits.push(‘mango‘); // 4
fruits; // [‘apple‘, ‘banana‘, ‘orange‘, ‘mango‘]  

And insert to the front with unshift():

fruits.unshift(‘grapes‘); // 5 
fruits; // [‘grapes‘, ‘apple‘, ‘banana‘, ‘orange‘, ‘mango‘]

Accessing Elements

Retrieve values by index, with the last item at array.length - 1:

let last = fruits[fruits.length - 1]; // ‘mango‘

Or find indexes by value with indexOf():

fruits.indexOf(‘orange‘); // 3
fruits.indexOf(‘cherry‘); // -1 (not found)

Removing Elements

We can remove from the end via pop():

let removed = fruits.pop(); 
removed; // ‘mango‘
fruits; // [‘grapes‘, ‘apple‘, ‘banana‘, ‘orange‘]

And similarly shift() removes first element:

fruits.shift();  
fruits; // [‘apple‘, ‘banana‘,‘orange‘]      

Multidimensional Arrays

We can store nested arrays for multi-level data:

let matrix = [
  [1, 2, 3],
  [4, 5, 6] 
];

matrix[1][2]; // 6 (rows x columns)

This provides a table-like structure with increased dimensionality.

Introducing jQuery

jQuery provides a robust API for navigating DOM elements and handling events. But it also includes handy utility methods – especially for arrays.

Consider this example selecting all <p> tags into a wrapper set:

let $paragraphs = $(‘p‘); // jQuery object

This special jQuery collection acts as an array. We can leverage all native array functionality like iterating with .each():

$paragraphs.each(function() {
  // element logic
});

Or chaining other jQuery methods:

$paragraphs.css(‘color‘, ‘red‘).addClass(‘text‘); 

Plus jQuery adds its own extensions. Next we‘ll explore two methods for removing values.

splice() – Remove by Index

Recall native .splice() allows deleting array elements by index. Let‘s revisit our languages example:

let languages = [‘Python‘, ‘JavaScript‘, ‘C++‘, ‘Java‘];

languages.splice(1, 1); // [‘Python‘, ‘C++‘, ‘Java‘];  

jQuery provides the same functionality for DOM collections:

$paragraphs.splice(1, 1); // remove second item

This directly trims matching elements out of the main set.

Some key strengths of .splice():

  • Works in-place on existing array/collection
  • Very fast since directly updates length
  • Handle any data types

Weaknesses to consider:

  • Permanently deletes values unless stored first
  • Requires target index value
  • Can cause unexpected issues if array length tracked separately

Overall .splice() makes easy index-based removal possible.

grep() – Filter on Value

Now let‘s revisit grep(), which filters arrays to new subsets without mutation. Given our languages:

let languages = [‘Python‘, ‘JavaScript‘, ‘C++‘, ‘Java‘];  

let filtered = $.grep(languages, value => value !== ‘JavaScript‘);

// [‘Python‘, ‘C++‘, ‘Java‘];

This iterates each value, adding to output if filter function returns true. This leaves the original intact while returning new filtered copy.

Applied to jQuery collections:

let $newParagraphs = $paragraphs.grep(function(i) {
  return $(this).text().length < 100; 
});

Here we get paragraphs under 100 characters.

Performance Tradeoffs

grep() has some performance implications to note:

Small Array Large Array
splice() 18 ms 47 ms
grep() 7 ms 712 ms

grep() iterates the entire collection checking every value, so grows slower compared to direct splice(). But for small sets it has good filtering speed.

Flexible Logic

The main advantages of .grep():

  • Leaves original array unchanged
  • Can target values directly
  • Custom test logic

Downsides to note:

  • Performance drop on large collections
  • More code if just needing simple removal

So .grep() excels when:

  • Avoiding side effects mutating source arrays
  • Precise conditional checking required
  • Duplicate eliminations across big data

Sorting Arrays

Related to filtering, jQuery has specialized sorting functionality via .sort(). Quick example:

let sorted = $fruits.sort(); // default ascending
let descending = $fruits.sort(function(a, b) {
  return b - a; 
})

We also access native methods like:

fruits.sort();
fruits.reverse(); // descending

Sorting brings order to data analysis and display – making finding or removing values simpler.

Real-World Recommendations

We‘ve covered core theory – now let‘s see some practical settings benefiting from these jQuery array capabilities:

1. Database Records

When retrieving query results, or processing forms/inputs, we may need to prune records:

// Fetch database rows
let records = db.findAll(); 

// Remove inactive
let active = $.grep(records, r => r.status === ‘active‘);

Here jQuery handles the record filtering gracefully.

2. Eliminate Duplicate UI Elements

For repeated dynamic content like comments, we can de-dupe before display:

let comments = getComments(); 

// Unique comments only
let unique = $.grep(comments, (c, i) => {
    return i === $.inArray(c, comments);
});

// Render unique set
displayComments(unique); 

This ensures smooth page interactions.

3. Priority Ordering

To sort elements by custom priority:

let tasks = [
  {id: 1, priority: 3},
  {id: 2, priority: 2},
  {id: 3, priority: 1}  
];

// Ascending priority
tasks.sort((a, b) => a.priority - b.priority);

// Render in order
renderTasks(tasks);

And we could grep() out low counts as well.

4. Bloom Filters

For advanced algorithms, jQuery versatility helps:

function BloomFilter(size) {
  // bit array, hash functions  
  this.filter = [];

  // check value against filters
  this.contains = function(value) {
    let indexes = getHashIndexes(value); 
    return indexes.every(i => filter[i]); 
  } 
}

let filter = new BloomFilter(500);
let subset = $.grep(values, filter.contains); 

Here we build a Performant hash set filter enabled via grep.

Conclusion

As we‘ve seen, jQuery provides excellent support for array operations like removing values – seamlessly improving raw JavaScript foundations. The syntax sugar around essential methods helps simplify complex application logic.

splice() enables fast index-based pruning in place. While grep() copies arrays based on flexible value testing. Understanding the performance profiles and side effects helps choose correctly.

And jQuery collections take array power right to our full app toolset – from DOM to data to advanced algorithms. By mastering arrays and leveraging abstraction libraries appropriately, we craft optimized programs ready for the demands of modern web development.

Similar Posts