Web Design Blog

Blog

JavaScript

10 Useful JavaScript Methods When Programming For Beginners

1. How to get all possible combinations of (string) elements inside of an array:

function scramble(arr) {
if (arr.length < 2) { return arr } return arr.flatMap((el, i) => {
const sub = arr.filter((_, j) => i != j)
return scramble(sub).map(el2 => el+el2)
})
}
console.log(scramble(["a", "b", "c", "d"]));
//[
'abcd', 'abdc', 'acbd',
'acdb', 'adbc', 'adcb',
'bacd', 'badc', 'bcad',
'bcda', 'bdac', 'bdca',
'cabd', 'cadb', 'cbad',
'cbda', 'cdab', 'cdba',
'dabc', 'dacb', 'dbac',
'dbca', 'dcab', 'dcba'
]

Explanation: Check if the array has a length less than 2. If so, return the array.
Otherwise, use recursion to add each element to the other and then return the result.

2. How to check for duplicates in an array:

function checkForDuplicates(array) {
let map = {};
array.forEach((value, index) => {
if(!map[value]) {
map[value] = 0;
}
map[value] += 1;
}
let newArray = Object.entries(map);
newArray.sort((a, b) => b[1] - a[1]);
return newArray[0][0] + " appears " + newArray[0][1] + " times in the array";
}

Explanation: Create a frequency map that stores the number of times each element appears in an array. Turn the frequency map (object) into an array and then sort it from greatest (number of occurrences) to least. Lastly, return a string, which says how many times the first Index number occurs in the original array.

3. How to create a staircase string:

function staircase(n) {
let line = Array(n+1).fill(" ");
for (let i = n - 1; i >= 0; i--) {
line[i] = "#";
console.log(line.join(""));
}
}

Explanation: Create a line size n. Loop through all integers from one less than n down to zero, and assign a hashtag to each line item. Console.log the joined line at each iteration throughout the loop to create the staircase.

4. How to create an array from 1 to n without a for-loop:

//first way
let array = Array.from({length: 10}, (_, k) => k + 1);
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
//second way
let array = Array(10).fill(0).map(e, i) => i + 1);
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Explanation: Array.from lets you create an array from whatever’s passed into it – so in this case an object of undefined elements of length 10. Then use an arrow function to fill those empty items with increments of 1.

You could also do the same by passing a number into the Array constructor, which fills the array with 10 empty items, in this case. Then, fill those items with zeros, and use map to convert them into increments of 1.

5. How to get rid of duplicates from an array:

let myArray = [1, 2, 3, 4, 5, 6, 7, 7, 7, 8, 9];
let myNewArray = [...new Set(myArray)];
console.log(myNewArray);

Explanation: Use the fact that a Set Constructor in JavaScript only allows each value to occur once. Use spread syntax to return all values from the newly formed Set.

6. How to check if an array is in ascending order:

function checkIfAscending(array) {
let static = array;
let sorted = array.slice().sort((a, b) => a - b);
if (String(static) === (String(sorted)) {
return "The array is sorted in ascending order";
}
else {
return "The array is not sorted in ascending order";
}
}

Explanation: Assign the passed in array to a new variable ‘static’. Also create a new array ‘sorted’ that sorts the passed in array in ascending order. Then compare both arrays by turning them into strings and checking if they are strictly equal.

7. How to Make a 2D array / grid based on n number of columns and rows

function makeGrid(numColumns, numRows) {
let grid = [];
for (let i = 0; i < numRows; i++) {
let row = [];
for (let j = 0; j < numColumns; j++) {
row.push(j + 1);
}
grid.push(row);
}
return grid;
}

Explanation: Create an array of rows based on the number of columns entered. Then push those rows into a grid array based on the number of rows entered. Use loops to create both the rows and columns.

8. How to find the word within a string that has the highest vowel count

function mostVowels(string) {
let array = string.split(" ");
let outerCount = 0;
let highest = "";
for (let i = 0; i < array.length; i++) {
let word = array[i];
let innerCount = 0;
for (let j = 0; j < word.length; j++) { if (word[j].match(/[aeiou]/i)) { innerCount ++; } } if (innerCount > outerCount) {
outerCount = innerCount;
highest = word;
}
}
return highest;
}
console.log(mostVowels('I went to the park today'));
//today

9. How to sum the digits of a given integer using recursion

function sumDigits(num) {
let array=String(num).split("").map(Number);
if(array.length === 0) {
return 0;
}
else {
return array[0] + sumDigits(array.slice(i).join(""));
}
}
console.log(sumDigits(679));
//22

10. How to Clone an Array

const vegetables = ['carrots', 'broccoli', 'radishes', 'onions'];
const vegetablesCopy = vegetables.slice();

or

const vegetables = ['carrots', 'broccoli', 'radishes', 'onions'];
const vegetablesCopy = [...vegetables];

or

const vegetables = ['carrots', 'broccoli', 'radishes', 'onions'];
const vegetablesCopy = Array.from(vegetables);

Lastly, (if the array is multi-dimensional)

let newArray = currentArray.map(function(arr) {
return arr.slice();
});

Leave a Reply

Your email address will not be published. Required fields are marked *