string and array methods
Sat Jun 29 2024 02:48:20 GMT+0000 (Coordinated Universal Time)
Saved by @NoFox420 #javascript
The spread operator (...) allows you to copy all elements from one array into another. It can also be used to concatenate multiple arrays into one. In the example below, both arr1 and arr2 have been spread into combinedArr: const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combinedArr = [...arr1, ...arr2]; console.log(combinedArr); // Output: [1, 2, 3, 4, 5, 6] An arrow function is an anonymous function expression and a shorter way to write functions. Anonymous means that the function does not have a name. Arrow functions are always anonymous. Here is the basic syntax: () => {} To create a named arrow function, you can assign the function to a variable: const exampleFunction = () => { // code goes here } To call a named arrow function expression, you can reference the function by its name. exampleArrowFunction(); Just like regular functions, arrow functions can accept multiple parameters. Here is an example of a named arrow function with one parameter: const greet = (name) => { console.log(`Hello, ${name}!`); }; If the function only has one parameter, you can omit the parentheses around the parameter list like this: const greet = name => { console.log(`Hello, ${name}!`); }; Just like regular functions, arrow functions can return values. Here is an example of an arrow function returning the result of multiplying two numbers: const multiplyTwoNumbers = (num1, num2) => { return num1 * num2; } // Output: 12 console.log(multiplyTwoNumbers(3, 4)); If the arrow function is returning a simple expression, you can omit the return keyword and the curly braces {}. This is called an implicit return. const multiplyTwoNumbers = (num1, num2) => num1 * num2; If your arrow function has multiple lines of code in the function body, then you need to use the return keyword and the curly braces {}. const getTax = (price) => { const taxRate = 0.08; const tax = price * taxRate; return tax; }; The map() method is used to iterate through an array and return a new array. It's helpful when you want to create a new array based on the values of an existing array. For example: const numbers = [1, 2, 3]; const doubledNumbers = numbers.map((number) => number * 2); // doubledNumbers will be [2, 4, 6] Notice that the map() method takes a function as an argument. This is called a callback function, which is a function that is passed to another function as an argument. In the example above, the callback function is (number) => number * 2, and it's run on each element in the numbers array. The map() method then returns a new array with the results. Right now the songsHTML is an array. If you tried to display this as is, you would see the songs separated by commas. This is not the desired outcome because you want to display the songs as a list. To fix this, you will need to join the array into a single string by using the join() method. The join() method is used to concatenate all the elements of an array into a single string. It takes an optional parameter called a separator which is used to separate each element of the array. For example: const exampleArr = ["This", "is", "a", "sentence"]; const sentence = exampleArr.join(" "); // Separator takes a space character console.log(sentence); // Output: "This is a sentence" Optional chaining (?.) helps prevent errors when accessing nested properties that might be null or undefined. For example: const user = { name: "Quincy", address: { city: "San Francisco", state: "CA", country: "USA", }, }; // Accessing nested properties without optional chaining const state = user.address.state; // CA // Accessing a non-existent nested property with optional chaining const zipCode = user.address?.zipCode; // Returns undefined instead of throwing an error The sort() method converts elements of an array into strings and sorts them in place based on their values in the UTF-16 encoding. const names = ["Tom", "Jessica", "Quincy", "Naomi"]; names.sort() // ["Jessica", "Naomi", "Quincy", "Tom"] To sort the songs in alphabetical order by title, you will need to pass in a compare callback function into your sort() method. Here is an example of sorting a list of fruits by name. const fruits = [ { name: "Apples", price: 0.99 }, { name: "Blueberries", price: 1.49 }, { name: "Grapes", price: 2.99 }, ]; fruits.sort((a, b) => { if (a.name < b.name) { return -1; } if (a.name > b.name) { return 1; } return 0; }); The sort() method accepts a compare callback function that defines the sort order. In this example, the first condition (a.name < b.name) checks if the name of the first fruit is less than the name of the second fruit. If so, the first fruit is sorted before the second fruit. Strings are compared lexicographically which means they are compared character by character. For example, "Apples" is less than "Bananas" because "A" comes before "B" in the alphabet. The reason why this example is returning numbers is because the sort() method is expecting a number to be returned. If you return a negative number, the first item is sorted before the second item. const fruits = [ { name: "Apples", price: 0.99 }, { name: "Blueberries", price: 1.49 }, { name: "Grapes", price: 2.99 }, ]; fruits.sort((a, b) => { if (a.name < b.name) { return -1; } if (a.name > b.name) { return 1; } return 0; }); The find() method retrieves the first element within an array that fulfills the conditions specified in the provided callback function. If no element satisfies the condition, the method returns undefined. In the example below, the find() method is used to find the first number greater than 25: const numbers = [10, 20, 30, 40, 50]; // Find the first number greater than 25 const foundNumber = numbers.find((number) => number > 25); console.log(foundNumber); // Output: 30 To get the index for the current song, you can use the indexOf() method. The indexOf() array method returns the first index at which a given element can be found in the array, or -1 if the element is not present. const animals = ["dog", "cat", "horse"]; animals.indexOf("cat") // 1 The forEach method is used to loop through an array and perform a function on each element of the array. For example, suppose you have an array of numbers and you want to log each number to the console. const numbers = [1, 2, 3, 4, 5]; // Using forEach to iterate through the array numbers.forEach((number) => { console.log(number); // 1, 2, 3, 4, 5 }); textContent sets the text of a node and allows you to set or retrieve the text content of an HTML element. <div id="example">This is some text content</div> Example Code const element = document.getElementById('example'); console.log(element.textContent); // Output: This is some text content In earlier steps, you learned how to work with the sort() method to sort the songs in alphabetical order. Another use case for the callback function is to randomize an array. One way to randomize an array of items would be to subtract 0.5 from Math.random() which produces random values that are either positive or negative. This makes the comparison result a mix of positive and negative values, leading to a random ordering of elements. const names = ["Tom", "Jessica", "Quincy", "Naomi"]; names.sort(() => Math.random() - 0.5); createElement() is a DOM method you can use to dynamically create an element using JavaScript. To use createElement(), you call it, then pass in the tag name as a string: // syntax document.createElement(tagName) // example document.createElement('div') You can also assign it to a variable: const divElement = document.createElement('div') Now that you've created the button, you need to assign it a text. To do this, you need to use the createTextNode() method of DOM. The createTextNode() method is used to create a text node. To use it, you call it and pass in the text as a string: document.createTextNode("your text") You can also assign it to a variable: const myText = document.createTextNode("your text") Now that you've created the resetButton, you need to assign it an id and aria-label attributes. JavaScript provides the id and ariaLabel properties you need to use for this. For example, element.id would set an id attribute, and element.ariaLabel would set an aria-label attribute. Both of them accept their values as a string. appendChild() lets you add a node or an element as the child of another element. In the example below, the text "Click me" would be attached to the button: const parentElement = document.createElement("button") const parentElementText = document.createTextNode("Click me") // attach the text "Click me" to the button parentElement.appendChild(parentElementText)
Comments