JavaScript Array Methods and Regular Expression Fundamentals

Filtering Objects with in Arrays

Arrays frequently store complex data structures like objects. Extracting specific items based on object properties requires iterating through the collection and evaluating conditions.

class Employee {
    constructor(title, yearsActive, division) {
        this.title = title;
        this.yearsActive = yearsActive;
        this.division = division;
    }
}

const staff1 = new Employee('Manager', 12, 'Sales');
const staff2 = new Employee('Analyst', 3, 'IT');
const staff3 = new Employee('Director', 8, 'HR');
const staff4 = new Employee('Intern', 1, 'Marketing');
const staffList = [staff1, staff2, staff3, staff4];

function extractSeniorMembers() {
    const seniors = [];
    for (let idx = 0; idx < staffList.length; idx++) {
        if (staffList[idx].yearsActive >= 5) {
            seniors.unshift(staffList[idx]);
        }
    }
    console.log(seniors);
}

const getSeniors = extractSeniorMembers;

Array Composition and Mixed Data Types

JavaScript arrays are zero-indexed collections where each item is called an element. Arrays are highly flexible and can contain a mix of data types, including other arrays, objects, or even functions.

const numericSet = [10, 20, 30, 40];
const mixedBag = ['text', null, undefined, 42.5];
const callableList = [
    () => console.log('Action A'),
    () => console.log('Action B'),
    () => console.log('Action C')
];

Adding and Removing Elements

Several methods allow direct mutation of an array's edges. push() appends one or more items to the tail, while pop() removes and returns the last item. Conversely, unshift() inserts elements at the begining, and shift() removes the first element.

const roster = ['Alice', 'Bob', 'Charlie'];
roster.unshift('Zoe', 'Xander');
console.log(roster); // Outputs: ['Zoe', 'Xander', 'Alice', 'Bob', 'Charlie']

Iterating Over Arrays

Beyond traditional for loops, the forEach() method provides a functional approach to traversal, exposing the current value, its index, and the full array during each cycle.

const designations = ['Admin', 'User', 'Guest', 'Moderator', 99];

designations.forEach((role, position, completeArray) => {
    console.log(role, position, completeArray);
});

Eliminating Duplicate Values

A common algorithm to deduplicate an array involves nested loops. By comparing each element against the rest, duplicates can be removed using splice(). When an item is removed, the inner loop counter must decrement to account for the shifted indices and shortened array length.

const readings = [5, 2, 8, 5, 5, 3, 2, 9, 1, 4, 8];

for (let outerIdx = 0; outerIdx < readings.length; outerIdx++) {
    for (let innerIdx = outerIdx + 1; innerIdx < readings.length; innerIdx++) {
        if (readings[outerIdx] === readings[innerIdx]) {
            readings.splice(innerIdx, 1);
            innerIdx--;
        }
    }
}

Array Utility Methods

Standard arrays offer numerous built-in utilities. concat() merges multiple arrays. join() serializes elements into a string with a specified delimiter. slice() extracts a portion without mutating the original. splice() alters the original by removing or inserting items. reverse() flips the order. sort() orders elements, defaulting to Unicode for strings, but accepting a comparator function for numeric or custom sorting.

const metrics = [45, 2, 100, 8, 15];
const sortedDescending = metrics.sort((val1, val2) => {
    return val2 - val1;
});
console.log(sortedDescending);

Regular Expressions in JavaScript

Regular expressions define search patterns for text manipulation.

  • Quantifiers: + (one or more), * (zero or more), ? (zero or one), {x,y} (between x and y occurrences), ^ (starts with), $ (ends with).
  • Character Classes: \w (word character including alphanumeric and underscore), \W (non-word character), \d (digit), \D (non-digit), \s (whitespace), \S (non-whitespace).
  • Brackets: [abc] matches a, b, or c. [^abc] matches anything except a, b, or c.
  • Modifiers: g (global search), i (case-insensitive).

Patterns can be instantiated via the RegExp constructor or literal syntax /pattern/. The test() method returns a boolean indicating a match. String methods seamlessly integrate with regular expressions:

  • search() returns the index of the first match.
  • match() retrieves all matching substrings.
  • replace() substitutes matched text with a new string.
  • split() divides a string into an array based on the regex pattern.

Tags: javascript Arrays regular expressions Array Deduplication ES6

Posted on Sat, 30 May 2026 23:09:16 +0000 by saltious