Happylab Logo
Published on

Day7: Array Cardio Day 2

Authors
js30

Project Introduction: Second round of array practice, including some, every, find, findIndex, and slice

Project Page: https://iris1114.github.io/javascript30/07_Array-Cardio-Day-2/index.html (no visual interface, please open console)

Sample Data

The exercise provides 2 sets of data with 5 questions total. The people data is used for questions 1-2, and comments data for questions 3-5.

const people = [
  { name: 'Wes', year: 1988 },
  { name: 'Kait', year: 1986 },
  { name: 'Irv', year: 1970 },
  { name: 'Lux', year: 2015 },
]

const comments = [
  { text: 'Love this!', id: 523423 },
  { text: 'Super good', id: 823423 },
  { text: 'You are the best', id: 2039842 },
  { text: 'Ramen is my fav food ever', id: 123523 },
  { text: 'Nice Nice Nice!', id: 542328 },
]

1. Is at least one person 19 or older?

Method: Use some() to test if at least one element in the array meets the condition. Returns true if at least one element matches, false otherwise.

Answer:

const ans1 = people.some((person) => {
  return new Date().getFullYear - person.year >= 19
})

console.log('some():', ans1) //true

2. Is everyone 19 or older?

Method: Use every() to test if all elements in the array meet the condition. Returns true if all elements match, false otherwise.

Answer:

const ans2 = people.every((person) => {
  return new Date().getFullYear - person.year >= 19
})

console.log('every():', ans2) //false

3. Find the comment with the ID of 823423

Method: Use find() which returns the first element that satisfies the provided testing function. Returns undefined if no element is found.

Answer:

const ans3 = comments.find((comment) => {
  return comment.id === 823423
})

console.log('find()', ans3) //{text: "Super good", id: 823423}

4. Find the index with this ID of 823423

Method: Use findIndex() to find the index of the first element in the array that satisfies the provided testing function. Returns -1 if no element is found.

Answer:

const index = comments.findIndex((comment) => {
  return comment.id === 823423
})

console.log('findIndex()', index) //1

5. Delete the comment with the ID of 823423

Method: Use slice() which returns a new array object containing a shallow copy of a portion of the original array, selected from begin to end (end not included). The original array will not be modified. Note that if you use splice(), it will modify the original array by removing and/or adding elements.

Answer:

const newComments = [...comments.slice(0, index), ...comments.slice(index + 1)]

console.log('newComments', newComments)

References

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find