DEV Community

Michael Flores
Michael Flores

Posted on

JavaScript Array Methods, String Methods, & Math.random()

Array Methods

First lets start with the built in JavaScript array methods.

Here are some common methods that DO NOT mutate (change) the original array:

.indexOf()

let array = [10, 20, 30, 40, 50];

// Find the index of element 30
let index = array.indexOf(30);
console.log(index); // Output: 2

// Search for an element that is not in the array
index = array.indexOf(60);
console.log(index); // Output: -1

// Search starting from index 3
index = array.indexOf(30, 3);
console.log(index); // Output: -1 (30 is before index 3)
Enter fullscreen mode Exit fullscreen mode

.slice(), shallow copy

let array = [1, 2, 3, 4, 5];

// Create a new array from index 1 to 3 (4 is not included)
let newArray = array.slice(1, 4);
console.log(newArray); // Output: [2, 3, 4]

// Create a new array from index 2 to the end
let anotherArray = array.slice(2);
console.log(anotherArray); // Output: [3, 4, 5]

// Copy the entire array
let copyArray = array.slice();
console.log(copyArray); // Output: [1, 2, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

.join()

let array = ['Apple', 'Banana', 'Cherry'];

// Join elements with a comma (default separator)
let joined = array.join();
console.log(joined); // Output: 'Apple,Banana,Cherry'

// Join elements with a custom separator (e.g., a space)
let joinedWithSpace = array.join(' ');
console.log(joinedWithSpace); // Output: 'Apple Banana Cherry'

// Join elements with a custom separator (e.g., a dash)
let joinedWithDash = array.join('-');
console.log(joinedWithDash); // Output: 'Apple-Banana-Cherry'

Enter fullscreen mode Exit fullscreen mode

.includes()

let array = [1, 2, 3, 4, 5];

// Check if the array includes the number 3
let hasThree = array.includes(3);
console.log(hasThree); // Output: true

// Check if the array includes the number 6
let hasSix = array.includes(6);
console.log(hasSix); // Output: false

// Check if the array includes the number 3, starting from index 2
let hasThreeFromIndexTwo = array.includes(3, 2);
console.log(hasThreeFromIndexTwo); // Output: true (3 is present starting from index 2)

// Check if the array includes the number 3, starting from index 4
let hasThreeFromIndexFour = array.includes(3, 4);
console.log(hasThreeFromIndexFour); // Output: false (3 is not present starting from index 4)

Enter fullscreen mode Exit fullscreen mode

Some common methods with React.

.map(), For arrays of primitive values (e.g., numbers, strings, booleans), the values themselves are copied into the new array (deep copy)

let numbers = [1, 2, 3, 4, 5];

// Create a new array with each element doubled
let doubled = numbers.map(x => x * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]

// Create a new array with the squares of each element
let squared = numbers.map(x => x ** 2);
console.log(squared); // Output: [1, 4, 9, 16, 25]

// Create a new array with element indexes as strings
let indexed = numbers.map((x, i) => `${i}: ${x}`);
console.log(indexed); // Output: ['0: 1', '1: 2', '2: 3', '3: 4', '4: 5']

Enter fullscreen mode Exit fullscreen mode

.filter()

let numbers = [1, 2, 3, 4, 5];

// Filter out elements less than 4
let filtered = numbers.filter(x => x >= 4);
console.log(filtered); // Output: [4, 5]

// Filter out odd numbers
let evenNumbers = numbers.filter(x => x % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]

// Filter an array of objects
let people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

// Filter people who are 30 or older
let adults = people.filter(person => person.age >= 30);
console.log(adults); // Output: [{ name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 }]

Enter fullscreen mode Exit fullscreen mode

.reduce()

let numbers = [1, 2, 3, 4, 5];

// Sum all elements in the array
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 15

// Find the maximum value in the array
let max = numbers.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue));
console.log(max); // Output: 5

// Create an object counting occurrences of each number
let countOccurrences = numbers.reduce((accumulator, currentValue) => {
  accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
  return accumulator;
}, {});
console.log(countOccurrences); // Output: { '1': 1, '2': 1, '3': 1, '4': 1, '5': 1 }

Enter fullscreen mode Exit fullscreen mode

Now some common array methods that DO mutate (change) the original array:

.splice()

let array = [1, 2, 3, 4, 5];

// Remove 2 elements starting from index 1
array.splice(1, 2); 
console.log(array); // Output: [1, 4, 5];

// Add elements starting from index 1
array.splice(1, 0, 'a', 'b'); 
console.log(array); // Output: [1, 'a', 'b', 4, 5];
Enter fullscreen mode Exit fullscreen mode

.unshift()

let array = [2, 3, 4];

// Add elements to the beginning
array.unshift(0, 1);
console.log(array); // Output: [0, 1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

.fill()

let array = [1, 2, 3, 4, 5];

// Fill the entire array with the value 0
array.fill(0);
console.log(array); // Output: [0, 0, 0, 0, 0]

// Fill a part of the array with the value 7
array.fill(7, 1, 4);
console.log(array); // Output: [0, 7, 7, 7, 0]

Enter fullscreen mode Exit fullscreen mode

.sort(), default is ascending

let numbers = [4, 2, 5, 1, 3];

// Sort numbers in ascending order
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 2, 3, 4, 5]

// Sort numbers in descending order
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [5, 4, 3, 2, 1]

// Sort strings
let strings = ['banana', 'apple', 'cherry'];
strings.sort();
console.log(strings); // Output: ['apple', 'banana', 'cherry']

Enter fullscreen mode Exit fullscreen mode

String Methods

Now lets talk about some of the built in JavaScript string methods.

String are immutable, meaning they cannot be changed once they are created.

Here are a few common JS string methods you might use.

.replace()

let original = 'hello';
// Replace characters
let replaced = original.replace('e', 'a');
console.log(replaced); // Output: 'hallo'
console.log(original); // Output: 'hello' (original string remains unchanged)
Enter fullscreen mode Exit fullscreen mode

.substring()

let original = 'hello';
// Get a substring
let substring = original.substring(1, 4);
console.log(substring); // Output: 'ell'
console.log(original); // Output: 'hello' (original string remains unchanged)
Enter fullscreen mode Exit fullscreen mode

.split()

let text = 'apple,banana,cherry';

// Split the string by commas
let fruits = text.split(',');
console.log(fruits); // Output: ['apple', 'banana', 'cherry']

// Split the string by commas with a limit of 2
let limitedFruits = text.split(',', 2);
console.log(limitedFruits); // Output: ['apple', 'banana']

// Split the string with no separator
let singleElementArray = text.split();
console.log(singleElementArray); // Output: ['apple,banana,cherry']

Enter fullscreen mode Exit fullscreen mode

.charAt()

let text = 'Hello, World!';

// Get the character at index 7
let char = text.charAt(7);
console.log(char); // Output: 'W'
Enter fullscreen mode Exit fullscreen mode

.charCodeAt()

let text = 'Hello, World!';

// Get the Unicode code of the character at index 7
let code = text.charCodeAt(7);
console.log(code); // Output: 87 (Unicode for 'W')
Enter fullscreen mode Exit fullscreen mode

.search()

let text = 'Hello, World!';

// Search for the first occurrence of 'World'
let index = text.search('World');
console.log(index); // Output: 7

// Search for a pattern using a regular expression
let regexIndex = text.search(/world/i); // Case-insensitive search
console.log(regexIndex); // Output: 7
Enter fullscreen mode Exit fullscreen mode

Math.random()

1. Random Number Between 0 and 4 (5 Items)

If you want to generate a random integer between 0 and 4 (inclusive), you can use:

let randomIndex = Math.floor(Math.random() * 5);
console.log(randomIndex); // Output: 0, 1, 2, 3, or 4
Enter fullscreen mode Exit fullscreen mode

2. Random Number Between 1 and 5 (1 through 5)

To generate a random integer between 1 and 5 (inclusive), you need to adjust the formula slightly:

let randomNumber = Math.floor(Math.random() * 5) + 1;
console.log(randomNumber); // Output: 1, 2, 3, 4, or 5
Enter fullscreen mode Exit fullscreen mode

There are definitely a lot more, but these are some common ones that I have ran into at some point.

Top comments (0)