📝
marcyannotes
  • Welcome
  • Student Guidelines & Policies
    • Student Handbook
    • AI Policy
    • Academic Calendar
  • Environment Setup
    • Local Environment Setup - Mac
    • Local Environment Setup - Windows
    • GitHub Setup
    • Postgres Setup
  • Fullstack Software Engineering Curriculum
    • Overview
    • How-Tos
      • How To Code at Marcy: Code Style Guide
      • How to Do Short Response and Coding Assignments
      • How to Debug
      • How to PEDAC
      • How to Create Projects with Vite
      • How to Deploy on GitHub Pages
      • How to Deploy on Render
    • Mod 0 - Command Line Interfaces, Git, and GitHub
      • Mod 0 Overview
      • Command Line Interfaces
      • Git & GitHub
      • Git Pulling & Merging
      • Git Branching & PRs
      • Pair Programming: BONUS
    • Mod 1 - JavaScriptFundamentals
      • Mod 1 Overview
      • Intro to Programming
      • Errors
      • Node & Node Modules
      • Variables, Functions & String Methods
      • Control Flow, typeof, and Math
      • Loops
      • Arrays
      • Objects
      • Higher Order Functions: Callbacks
      • Higher Order Functions: Array Methods
      • Regex
    • Mod 2 - HTML, CSS & the DOM
      • Mod 2 Overview
      • HTML
      • CSS
      • Accessibility (a11y)
      • The DOM
      • Events
      • Forms
      • The Box Model and Positioning
      • Flexbox
      • Grid & Media Queries
      • ESModules
      • LocalStorage
    • Mod 3 - Async & APIs
      • Mod 3 Overview
      • Promises
      • Fetch
      • Building a Fetching App
      • Async & Await
    • Mod 4 - Project Week!
      • Project Week Overview
    • Mod 5 - Object-Oriented Programming
      • Mod 5 Overview
      • Intro to OOP, Encapsulation, Factory Functions, and Closure
      • Classes
      • Private & Static
      • Has Many/Belongs To
      • Polymorphism
    • Mod 6 - Data Structures & Algorithms
      • Mod 6 Overview
      • Stacks & Queues
      • Nodes & Linked Lists
      • Singly & Doubly Linked Lists
      • Recursion
      • Trees
    • Mod 7 - React
      • Mod 7 Overview
      • Intro to React
      • Events, State, and Forms
      • Fetching with useEffect
      • Building a Flashcards App
      • React Context
      • Global Context Pattern
      • React Router
    • Mod 8 - Backend
      • Mod 8 Overview
      • Intro to Express
      • Building a Static Web Server with Middleware
      • Securing API Keys with Environment Variables
      • Building a RESTful API with MVC
      • SQL and Databases
      • JOIN (Association) SQL Queries
      • Knex
      • Your First Fullstack App!
      • Migrations & Seeds
      • Schema Design & Normalization
      • Hashing Passwords with Bcrypt
  • Code Challenge Curriculum
    • Unit 0
      • Lecture: Functions in JS
      • CC-00: Functions and Console Logs
      • CC-01: Conditionals
      • CC-02: Conditionals 2
    • Unit 1
      • CC-03: For Loops
      • CC-04: For Loops and Conditionals
      • CC-05: For Loops and Conditionals 2
    • Unit 2
      • CC-06: String Mutations
      • CC-07: Array Iteration
      • CC-08: String Mutation and Array Iteration
      • CC-09: Array Mutations
      • CC-10: Reading Objects
      • CC-11: Objects
      • CC-12: Objects
      • Unit 2 Diagnostic
    • Unit 3
      • Intro to PEDAC (and Algorithms)
      • validTime
      • fizzBuzz (array)
      • digitSumDifference
      • firstNotRepeating
      • compareEvenAndOddSum
      • countVowelConsonants
      • finalHP
      • canMakeTriangle
    • Unit 4
    • Unit 5
    • Unit 6
    • Unit 7
    • Unit 8
    • Sorting
Powered by GitBook
On this page
  • Code Challenge
  • BONUS
  1. Code Challenge Curriculum
  2. Unit 2

CC-12: Objects

with Carmen Salas • 2024/10/23

Code Challenge

  1. Write a function named stringLengths that takes in an array of strings as an input, and returns an object, where the keys are all the strings in the array, and the value of each key represents the length of that string.

const stringLengths = (strArr) => {
  let res = {};
  strArray.forEach((str) => res[str] = str.length);
  return res;
}

const instructors = ["Ben", "Motun", "Gonzolo", "Itzel"]
console.log(stringLengths(instructors)) // { Ben: 3, Motun: 5, Gonzolo: 7, Itzel: 5 }
  1. Write a function named stringCount that takes in an array of strings and returns an object where the keys are the strings from the array and the value of each key is a count of how many times the string appears in the object. If there are duplicate strings the values should reflect that.

// for each approach
const stringCount = (strArray) => {
  let res = {};
  strArray.forEach((str) => (res[str]) ? res[str]++ : res[str]=1);
  return res;
}

// reduce approach
const stringCount = (strArray) => {
  return strArray.reduce((res, str) => {
    (res[str]) ? res[str]++ : res[str]=1
    return res;
  }, {});
}

const words = ["apple", "orange", "peach", "pear", "apple"]
console.log(stringCount(words)) // { apple: 2, orange: 1, peach: 1, pear: 1 }

BONUS

  1. Write a function named highestFrequencyString that takes in an array of strings and returns the string with the highest frequency in the array and how many times it appears.

// method mania
const highestFrequencyString = (strArray) => {
  // so janky can we do better?
  let res = {};
  strArray.forEach((str) => (res[str]) ? res[str]++ : res[str]=1);
  // var reuse because i'm a degenerate
  res = Object.entries(res).sort((a,b) => b[1]-a[1])[0];
  return `${res[0]} appears ${res[1]} times in the array.`
}
// for loop because you hate yourself
const highestFrequencyString = (strArray) => {
  strArray.sort((a,b) => a <= b ? -1 : 1);
  let max = 1;
  let curr = 0;
  let res = strArray[0];
  for (let i = 0; i < strArray.length-1; i++) {
    if (strArray[i] === strArray[i+1]) {
      curr++;
    } else {
      if (max < ++curr) {
        max = curr;
        res = strArray[i];
      }
      curr = 0;
    }
  }
  return `${res} appears ${max} times in the array.`
}


const fruits = ["apple", "orange", "apple", "peach", "pear", "apple", "peach"]
console.log(highestFrequencyString(fruits)); // "apple appears 3 times in the array."
PreviousCC-11: ObjectsNextUnit 2 Diagnostic

Last updated 7 months ago

forEach and reduce have very similar performance for this function. See here.

Using purely Array and Object methods perform very similarly to doing it manually with a for loop. See here.

benchmark
benchmark