Skip to main content

[[TOC]]

Overview


Array to string


If you have an array of users, and you'd like to get the name of each user separated by a comma. What would you do for that?

.map() to remove the users from the array and then the .join() to join them to a string.

const users = [{
id: 1,
name: "Solo Stroup"
}, {
id: 2,
name: "Liz Funkhouser"
}];

const userNamesArray = users.map(user => user.name);
console.log(userNamesArray); // ["Solo Stroup", "Liz Funkhouser"];

const csv = userNamesArray.join(", ");
console.log(csv); // "Solo Stroup, Liz Funkhouser"

//or simplfied:

const users = [{
id: 1,
name: "Solo Stroup"
}, {
id: 2,
name: "Liz Funkhouser"
}];

const csv = users.map(user => user.name).join(", ");
console.log(csv); // "Solo Stroup, Liz Funkhouser"

Applying that to html: This way is preferred because this is used regularly in front end libraries like React and Angular

const html = `<ul>
${users.map(user => `<li>${user.name}</li>`).join("")}
</ul>`;
console.log(html); // <ul> <li>Solo Stroup</li><li>Liz Funkhouser</li> </ul>

Nutrition table HTML example


//missing the part to put the <td> on separate lines.
export const renderTableRows = rows => {

const html = `<tr>
${rows.map(row => `<td>${row[0]}</td>` + `<td>${row[1]}</td>`).join("")}
</tr>`;
console.log(html);
return html;
}

// Apparently you didn't need to do that in the solution :)
export const renderTableRows = rows => {
return rows.map(row => `<tr><td>${row[0]}</td><td>${row[1]}</td></tr>`).join("");
}

Countries Revisited


How would we rewrite this?

//this working code from the other page
export const getDropdown = (countries) => {
let htmlstring = `<option value="">Please select</option>"`
countries.forEach(country => {
htmlstring +=`<option value="${country.toLowerCase()}">${country}</option>`

});
console.log(htmlstring)
return htmlstring;


}
//into something like the previous example?
export const renderTableRows = rows => {
return rows.map(row => `<tr><td>${row[0]}</td><td>${row[1]}</td></tr>`).join("");
}

//like this:
export const getDropdown = countries => {
return `<option value = "" >Please select</option>` + countries.map(country => `<option value = "${country.toLowerCase()}">${country}</option>`).join("");
}

HTML: image.png

Lesser used array methods


Array.every(callback)


MDN Docs The Array .every(callback) method returns true when every item in the array satisfies the condition provided in the callback.

const numbers = [15, 10, 20];

const allAbove10 = numbers.every(number => number >= 10); // true
const allAbove15 = numbers.every(number => number >= 15); // false

Array.some(callback)


MDN Docs The Array .some(callback) method returns true when ONE item in the array satisfies the condition provided in the callback.

const numbers = [15, 10, 20];

const someOver18 = numbers.some(number => number >= 18); // true
const someUnder10 = numbers.some(number => number < 10); // false

Grades below 10 problem


Write out a function that says you should increase the grades if one of the grades isn't passing (equal or above 10)

/**
* @param {number[]} grades
*/
const shouldAdjustGrades = grades => {
const allAbove10 = grades.some(grade => grade < 10);
return allAbove10;
}


// Sample usage - do not modify
shouldAdjustGrades([10, 12, 10, 14]); // false
shouldAdjustGrades([12, 8, 17]); // true

Cancel exam problem


Complete the function shouldCancelExam such that it returns true when the exam needs to be canceled. An exam must be canceled if all the students' grades were very high (18 and above).

const shouldCancelExam = grades => {
const allAbove10 = grades.every(grade => grade >= 18);
return allAbove10;

}


// Sample usage - do not modify
console.log(shouldCancelExam([10, 12, 10, 14])); // false
console.log(shouldCancelExam([18, 4])); // false
console.log(shouldCancelExam([19, 18, 18])); // true

Deleting Items


You can empty an array by setting its length to 0.

const animals= ["dog", "cat"];
animals.length = 0;

console.log(animals); // []

Now, the question is...why can we do this with a const? Doesn't const make the variable immutable? No. We are just setting the length of the aminals array to 0.

Array.splice()


You can delete specific items from an array using this method.

  • To delete the 1st element of an array, you call .splice(0, 1).
  • To delete 3 elements starting from the 2nd position, you call .splice(1, 3).
  • If you call .splice(1), then it will remove all the items starting from the 2nd position (index 1).
const items = ["Pen", "Paper", "Staples"];
const deletedItem = items.splice(0, 1); // removes one element at index 0
console.log(deletedItem); // ["Pen"]

console.log(items); // ["Paper", "Staples"]

//The .splice method returns an array of the elements removed. :)

Empty the array


const resetApps = apps => {
return apps.length = 0

}

// Sample usage - do not modify
const apps = ["Calculator", "Whatsapp", "Chrome", "Firefox"]
console.log(resetApps(apps));

Remove element from array


Complete the function removeFirstApp such that it removes the first element of the apps array it receives and returns the new array (which should not contain the item that was removed).

const removeFirstApp = apps => {
apps.splice(0, 1);
console.log(apps);
}

// Sample usage - do not modify
const apps = ["Calculator", "Whatsapp", "Chrome", "Firefox"]
console.log(removeFirstApp(apps)); // ["Whatsapp", "Chrome", "Firefox"]

Remove second app


const removeSecondApp = apps => {
apps.splice(1,1);
return apps

}

// Sample usage
const apps = ["Calculator", "Whatsapp", "Chrome", "Firefox"]
console.log(removeSecondApp(apps)); // ["Calculator", "Chrome", "Firefox"]

Recap


  • The Array .every(callback) method returns true when every item in the array satisfies the condition provided in the callback.
  • The Array .some(callback) method returns true when at least one item in the array satisfies the condition provided in the callback.
  • You can empty an array by setting its length to 0.
  • .splice(start[, deleteCount]) removes items from the array from the start index. The number of items it will remove is specified by deleteCount.
  • If you omit deleteCount, it will remove all the items as of the start index.