DEV Community

Cover image for Master JavaScript Arrays: Mutate, Map & Sort Like a Pro
Shubham Tiwari
Shubham Tiwari

Posted on

Master JavaScript Arrays: Mutate, Map & Sort Like a Pro

Hello my fellow frontend developer friends, today i will be discussing array methods on steroids. You must buckle your seatbelt as this journey is going to be a bit long.

  • I'll be creating my code snippets on Scribbler.live first, which is a fantastic platform that allows you to run a JavaScript Notebook, Online Compiler, and Editor without the need for manual setup.
  • Additionally, I'll be including a link to code snippets that includes all of the code examples so you can open the snippet and run it yourself to see the results.
  • i will be using scrib.show from scribbler.live, it is equivalent to console.log

Let's dive in.

Table of contents

Mutating array methods

These methods modifies the original arrat itself, these includes:

  • push - adds a new element to the array at the end
  • pop - removes an element from the end of the array
  • unshit - adds a new element to the beginning of the array
  • shift - removes an element from the beginning of the array
  • sort - sort the array in ascending or descending order
  • reverse - reverse the array from end to start
  • splice - could add, remove or replace elements from any index
  • fill - could bulk add the elements to the array with same value.

📌 Use Case: Managing a Cart in an E-commerce App

Sample codes

// mutating methods
const tags = ["html", "css", "javascript", "react"]

// push
tags.push("nextjs")
scrib.show("Push - ",tags)

// pop
tags.pop()
scrib.show("Pop - ",tags)

// unshift
tags.unshift("nextjs")
scrib.show("Unshift - ",tags)

// shift
tags.shift()
scrib.show("Shift - ",tags)

// sort
tags.sort()
scrib.show("Sort - ",tags)

// reverse
tags.reverse()
scrib.show("Reverse - ",tags)

// splice
tags.splice(0,0,"HTML") // will replace first index element with HTML
tags.splice(0,2,"HTML") // will delete first 2 elements and replace with HTML
scrib.show("Splice - ",tags)

// fill
tags.fill("Scribbler",0,2) // replace first elements with Scribbler
scrib.show("Fill - ",tags)
Enter fullscreen mode Exit fullscreen mode

Conditional push

// Methods on steroids - conditional push
const tags = ["html", "css", "javascript", "react"]

const addValidTags = (isTagValid) => {
  const invalidTag = "java"
  if(isTagValid !== invalidTag){
    tags.push(isTagValid)
  }
}
addValidTags("nextjs") // will add this to the array
addValidTags("java") // won't add this to the array
scrib.show(tags)
Enter fullscreen mode Exit fullscreen mode

Conditional filtering

// Methods on steroids - conditional filtering
const tags = ["html", "css", "javascript", "react"]

const filters = (filterName) => {
  if(filterName === "sort"){
    tags.sort()
    return tags
  }
  else if(filterName === "reverse"){
    tags.reverse()
    return tags
  }
  else {
    return tags
  }
}

filters("sort") // first sort the tags
filters("reverse") // then reverse it
Enter fullscreen mode Exit fullscreen mode

Checkout this embed to run the code example mentioned above

Non mutating methods

These methods performs some operations but on a new array instead of changing the original array, these includes:

  • filter - filters an array based on a callback function
  • map - map over the array based on a callback function
  • slice - extract out a part of the array
  • concat - merge 2 arrays
  • flat - flatten the multi-dimensional or nested arrays
  • flatMap - flatten the multi-dimensional or nested arrays by 1 level and does the mapping with a callback function with it.

📌 Use Case: Filtering Products Based on Category & Creating a New List

Sample code

const technologies = [
  {
    name:"HTML",
    type:"Frontend"
  },
  {
    name:"CSS",
    type:"Frontend"
  },
  {
    name:"JS",
    type:"Frontend"
  },
  {
    name:"React",
    type:"Frontend"
  },
  {
    name:"Java",
    type:"Backend"
  },
  {
    name:"Node",
    type:"Backend"
  },
]

const otherTechnologies = [
  {
    name:"Python",
    type:"Backend"
  },
  {
    name:"Rust",
    type:"Backend"
  },
]

// filter method
const frontendTechs = technologies.filter(technology => {
  if(technology.type === "Frontend"){
    return technology
  }
})
scrib.show("Frontend techs - ",frontendTechs) // will return an array with items with type Frontend

// map method
const frontendTechsNames = frontendTechs.map(technology => technology.name) // will return an array with technology names with type Frontend
scrib.show("Frontend tech names - ",frontendTechsNames) // will return an array with items with type Frontend


// slice method
const firstThreeItems = technologies.slice(0,3) // first three items in the array
scrib.show("First three items - ",firstThreeItems)

// concat method
const combinedTechnologies = technologies.concat(otherTechnologies)
scrib.show("Combined technologies - ",combinedTechnologies)

// flat method
const nestedArrays = ["HTML","CSS","JS",["REACT","NEXTJS", ["TAILWIND",["SCSS"]]]]
const oneLevelFlat = nestedArrays.flat()
const twoLevelFlat = nestedArrays.flat(2)
const infinityLevelFlat = nestedArrays.flat(Infinity)
scrib.show(oneLevelFlat)
scrib.show(twoLevelFlat)
scrib.show(infinityLevelFlat)

// flatMap method
const webTechnologies = ["HTML","CSS","JS"]
const flatAndLowercase = webTechnologies.flatMap(technology => technology.toLowerCase())
scrib.show(flatAndLowercase)
Enter fullscreen mode Exit fullscreen mode

Chaining of methods

// Chaining of methods
const technologies = [
  {
    name:"HTML",
    type:"Frontend"
  },
  {
    name:"CSS",
    type:"Frontend"
  },
  {
    name:"JS",
    type:"Frontend"
  },
  {
    name:"React",
    type:"Frontend"
  },
  {
    name:"Java",
    type:"Backend"
  },
  {
    name:"Node",
    type:"Backend"
  },
]

// Filter and map
const frontendNamesByChaining = technologies.filter(technology => technology.type === "Frontend").map(technology => technology.name)
scrib.show(frontendNamesByChaining)

// flat and map
const nestedArrays = ["HTML","CSS","JS",["REACT","NEXTJS", ["TAILWIND",["SCSS"]]]]
const flatAndMapChaining = nestedArrays.flat(Infinity).map(technology => technology.toLowerCase())
scrib.show(flatAndMapChaining)
Enter fullscreen mode Exit fullscreen mode

Checkout this embed to run the code example mentioned above

Searching and finding

These methods helps in finding a element or it index in an array, these includes:

  • find - to find an element directly in the array
  • findIndex - to find the index of element directly in the array
  • indexOf - find the index of the first occurence of an element in the array
  • lastIndex - find the index of the last occurence of an element in the array.
  • includes - checks if an array contains a value and returns true/false
  • some - checks if at least one element meets a condition
  • every - checks if all the elements meets a condition

📌 Use Case: Searching for a User in a Database

Sample codes

// Searching and indexing methods
const humans = [
  {
    id: 1001,
    name: "Bruce",
    isAvailable: true
  },
   {
    id: 1002,
    name: "Clark",
    isAvailable: true
  },
   {
    id: 1003,
    name: "Diana",
    isAvailable: true
  },
   {
    id: 1004,
    name: "Barry",
    isAvailable: false
  }
]

const hereos = ["Batman","Superman","Wonder woman","Flash"]

// find method
const findBatman = humans.find(hero => hero.name === "Bruce")
scrib.show(findBatman) // { "id": 1001, "name": "Bruce", "isAvailable": true }

// findIndex method
const findSupermanIndex = humans.findIndex(hero => hero.name === "Clark")
scrib.show(findSupermanIndex) // 1

// indexOf method
const findFlash = hereos.indexOf("Flash")
scrib.show(findFlash) // 3

// lastIndex
const findSuperman = hereos.lastIndexOf("Superman")
scrib.show(findSuperman) // 1

// includes
const wonderWomanInTeam = hereos.includes("Wonder woman")
scrib.show(wonderWomanInTeam) // true

// some 
const availableHeros = humans.some(human => human.isAvailable === true)
scrib.show(availableHeros) // true

// every
const allHeroesAvailable = humans.every(human => human.isAvailable === true)
scrib.show(allHeroesAvailable) // false
Enter fullscreen mode Exit fullscreen mode

Chaining with other methods

// Chaining with other array methods like filter
const humans = [
  {
    id: 1001,
    name: "Bruce",
    isAvailable: true
  },
   {
    id: 1002,
    name: "Clark",
    isAvailable: true
  },
   {
    id: 1003,
    name: "Diana",
    isAvailable: true
  },
   {
    id: 1004,
    name: "Barry",
    isAvailable: false
  }
]

const isBatmanAvailable = humans.filter(human => human.isAvailable).find(human => human.name === "Bruce")
scrib.show(isBatmanAvailable)
Enter fullscreen mode Exit fullscreen mode

Checkout this embed to run the code example mentioned above

Iteration Methods

  • forEach(callback) → Loops through elements, returns undefined for each element
  • entries() → Returns an iterator with key-value pairs
  • keys() → Returns an iterator with indexes/keys
  • values() → Returns an iterator with values

📌 Use Case: Displaying Product Listings in a UI

Sample codes

const humans = [
  {
    id: 1001,
    name: "Bruce",
    isAvailable: true
  },
   {
    id: 1002,
    name: "Clark",
    isAvailable: true
  },
   {
    id: 1003,
    name: "Diana",
    isAvailable: true
  },
   {
    id: 1004,
    name: "Barry",
    isAvailable: false
  }
]

// forEach loop
humans.forEach(human => human.hasSuperPowers = true)
scrib.show("For each loop - ", humans)

// entries
scrib.show("ENTRIES")
for (const [key, value] of Object.entries(humans)) {
  scrib.show(`Key: ${key} and `, "Value: ",value);
}

// keys
scrib.show("KEYS")
for (const key of Object.keys(humans)) {
  scrib.show(`Key: ${key}`);
}

// values
scrib.show("VALUES")
for (const value of Object.values(humans)) {
  scrib.show("Values: ",value);
}
Enter fullscreen mode Exit fullscreen mode

Checkout this embed to run the code example mentioned above

Reducing & Aggregation

  • reduce(callback, initialValue) → execute a callback function on each element of an array to produce a single accumulated result.
  • reduceRight(callback, initialValue) → Same as reduce() but processes from right to left

📌 Use Case: Calculating the Total Price in a Shopping Cart

Sample code

// Flattening single level nested arrays with reduce
const technologies = [["HTML", "CSS"], ["JS", "TS"], ["REACT", "NEXTJS"]];

const flatArray = technologies.reduce((acc, arr) => acc.concat(arr), []);
scrib.show(flatArray);

const flatArrayFromRight = technologies.reduceRight((acc, arr) => acc.concat(arr), []);
scrib.show(flatArrayFromRight);
Enter fullscreen mode Exit fullscreen mode

Countring occurences of a properties

const sentence = "Hello i am bruce , bruce wayne , founder of wayne enterprises";

const wordCount = sentence.split(" ").reduce((acc, word) => {
  acc[word] = (acc[word] || 0) + 1;
  return acc;
}, {});
scrib.show(wordCount)
Enter fullscreen mode Exit fullscreen mode

Grouping things

const superheroes = [
  { name: "Batman", team: "Justice League" },
  { name: "Superman", team: "Justice League" },
  { name: "Flash", team: "Justice League" },
  { name: "Iron man", team: "Avengers" },
  { name: "Thor", team: "Avengers" },
  { name: "Captain america", team: "Avengers" },
];

const groupByTeam = superheroes.reduce((acc, superhero) => {
  (acc[superhero.team] = acc[superhero.team] || []).push(superhero);
  return acc;
}, {});

const teamJusticeLeague = groupByTeam["Justice League"]
const teamAvengers = groupByTeam["Avengers"]
scrib.show("Group team:",groupByTeam)
scrib.show("Justice League:",groupByTeam["Justice League"])
scrib.show("Avengers:",groupByTeam["Avengers"])
Enter fullscreen mode Exit fullscreen mode

Checkout this embed to run the code example mentioned above

Joining and converting

  • join(separator) → Converts array to a string
  • toString() → Converts array to a comma-separated string

📌 Use Case: Formatting Tags for SEO-Friendly URLs

Sample codes

join method

// join method
const superheroes = ["Batman", "Superman", "Flash", "Wonder woman"];

const joinHeroes = superheroes.join("") // join without a separator
const joinHeroesWithHyphen = superheroes.join("-") // join with a hyphen as a separator
scrib.show("Without seperator - ",joinHeroes)
scrib.show("Without seperator as hyphen - ",joinHeroesWithHyphen)
Enter fullscreen mode Exit fullscreen mode

toString method

// toString
const superheroes = ["Batman", "Superman", "Flash", "Wonder woman"];
const superheroesString = superheroes.toString();
scrib.show("Superheroes array as string separated by comma - ",superheroesString)
Enter fullscreen mode Exit fullscreen mode

Chaining with other methods

// Chaining with other methods
const superheroes = ["Batman", "Superman", "Flash", "Wonder woman"];
const heroesWithLowerCase = superheroes.join(" ").toLowerCase()
scrib.show("Chaining with other methods - ",heroesWithLowerCase)
Enter fullscreen mode Exit fullscreen mode

Checkout this embed to run the code example mentioned above

Creating and Copying Methods (Advanced)

  • copyWithin(target, start, end) → Copies part of the array to another location
  • from(arrayLike, mapFn) → Creates an array from an array-like object
  • of(element1, element2, ...) → Creates an array from given elements

📌 Use Case: Converting a NodeList to an Array in DOM Manipulation

Sample codes

Copy within method

// copyWithin method, rarely used
const superheroes = ["Batman", "Superman", "Flash", "Wonder woman"];

const copyFromIndex0To2 = superheroes.copyWithin(0, 2)
scrib.show(copyFromIndex0To2)
Enter fullscreen mode Exit fullscreen mode

From method

// from method
const batman = "Batman"
const arrayFromString = Array.from(batman)
scrib.show(arrayFromString)
Enter fullscreen mode Exit fullscreen mode

Of method

const createArrayFromWords = Array.of("Batman", "Superman", "Flash", "Wonder woman")
scrib.show(createArrayFromWords)
Enter fullscreen mode Exit fullscreen mode

Chaining with other method

// Chaining with other methods
const superhereos = "Batman Superman Flash Wonder woman";
const convertSuperheroesToArray = superhereos.split(" ").join("-");
scrib.show()
scrib.show(Array.from(convertSuperheroesToArray))
Enter fullscreen mode Exit fullscreen mode

Checkout this embed to run the code example mentioned above

That's it for this post, Let me know if i could do any improvements in this article. Also, do check Scribbler.live website.

You can contact me on -

Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

You can help me with some donation at the link below Thank you👇👇
https://www.buymeacoffee.com/waaduheck

Also check these posts as well




Top comments (0)