Thursday, November 12, 2020

Arrays 3 : Instance Methods pop() push() shift() unshift() slice() splice() indexOf() lastIndexOf() includes()

 /*
Instance Methods
*/

pop() push() shift() unshift() slice() splice() indexOf() lastIndexOf() includes()


// Display all bun types with " or " - use join()

// We have a string "hot dogs,hamburgers,sausages,corn" - use split() to turn it into a string
const foodString = "hot dogs,hamburgers,sausages,corn";
// console.log(foodString.split(','));
// console.log([...foodString]);

// console.log(foodString.split(''));
// console.log([...foodString]);
// These two work the same, it's because you're splitting with nothing.

// take the last item off toppings with pop()
const lastItem = toppings.pop();
// console.log(lastItem);

// add it back with push()
const t2 = toppings.push(lastItem);
// console.log(t2);

// take the first item off toppings with shift()
const firstItem = toppings.shift();
// console.log(firstItem);

// add it back in with unshift()
const t3 = toppings.unshift(firstItem);
// console.log(t3);

// Do the last four,but immutable (with spreads and new variables)
let newToppings = toppings.slice(0, toppings.length - 1);
newToppings = [...newToppings, toppings[toppings.length - 1]];
// console.log(newToppings);

newToppings = toppings.slice(1, toppings.length - 1);
newToppings = ['Mushrooms', ...newToppings];
// console.log(newToppings);

// Make a copy of the toppings array with slice()
const toppingsCopy = toppings.slice(0) // end is optional
// console.log(toppingsCopy);

// Make a copy of the toppings array with a spread
const toppingsCopy2 = [...toppings] // end is optional
// console.log(toppingsCopy2);

// take out items 3 to 5 of your new toppings array with splice()
// console.log(newToppings);
newToppings = newToppings.splice(2, 3);
// console.log(newToppings);

// find the index of Avocado with indexOf() / lastIndexOf()
const avoIndex = toppings.indexOf('Avocado');
// console.log(avoIndex);

const avoIndex2 = toppings.lastIndexOf('Avocado');
// console.log(avoIndex2);


// Check if hot sauce is in the toppings with includes()
const isInToppings = toppings.includes('Hot Sauce');
// console.log(isInToppings);
// add it if it's not
if (!isInToppings) {
toppings.push('Hot Sauce')
}
// console.log(toppings);

// flip those toppings around with reverse()

toppings.reverse();
// console.log(toppings); 

No comments:

Post a Comment

Arrays 4 : Callback Methods find() filter() some() every() sort()

  /* Callback Methods */ // const util = { // findBurgRating: function(singleFeedback) { // return singleFeedback.comment....