DEV Community

Cover image for You are JS noob without knowing these methods
Milan Mohapatra
Milan Mohapatra

Posted on • Updated on

You are JS noob without knowing these methods

Most important methods of your JavaScript codebase.

In day-to-day development with JavaScript in the form of frontend framework or backend framework, I use some methods to manipulate arrays or objects, these are so frequently used in project development and fun to do.


What I mentioned after are not the only methods for Arrays and Objects, these are just frequent and popular ones.

find()

  • To find the single element present in an array.
  • It returns the first element that satisfies the condition.
  • It takes one callback function as an argument, callback function returns a boolean.
  • If the condition is false with every element it returns undefind.
  • UseCase: Find a student whose rank is 5, in this case, it will return one object.
students.find((student) => {
    return student.rank == 5;
  })

// { id: 5, name: 'nitish', rank: 5 }
Enter fullscreen mode Exit fullscreen mode

filter()

  • To find the array of elements present in the array.
  • It returns one array of elements that satisfy the conditions.
  • It takes one callback function as an argument, callback function returns a boolean.
  • If the condition is false with every element it returns an empty array [].
  • UseCase: Find the top three students.
students.filter((student) => {
    return student.rank <= 3;
  })

/*
[
  { id: 1, name: 'milan', rank: 1 },
  { id: 2, name: 'kiran', rank: 2 },
  { id: 3, name: 'priya', rank: 3 } 
]
*/
Enter fullscreen mode Exit fullscreen mode

map()

  • To transfer the array of elements.
  • Return the array with the same number of elements present.
  • It takes one callback function and returns the expression to transform the array.
  • UseCase: Create an array of strings declaring who has what rank.
const result = students.map((student) => `${student.name} has rank: ${student.rank}`);

console.log(students)
console.log(result)

/*
[
  { id: 1, name: 'milan', rank: 1, fee: 1000 },
  { id: 2, name: 'kiran', rank: 2, fee: 2000 },
  { id: 3, name: 'nitish', rank: 3, fee: 3000 },
  { id: 4, name: 'priya', rank: 4, fee: 4000 },
  { id: 5, name: 'pratyush', rank: 4, fee: 5000 }
]
[
  'milan has rank: 1',
  'kiran has rank: 2',
  'nitish has rank: 3',
  'priya has rank: 4',
  'pratyush has rank: 4'
]
*/
Enter fullscreen mode Exit fullscreen mode

reduce()

  • It can convert one array to a single element.
  • It takes one callback and one initial accumulator value(option) and returns one digested accumulator value.
  • If you do not initialize the accumulator value it will consider the first element of the array as the initial accumulator value.
  • UseCase: Find the sum of fees of students.
students.reduce((acc, next) => {
    acc += next.fee
    return acc;
  }, 0)

// 15000
Enter fullscreen mode Exit fullscreen mode

every()

  • Return true, if the condition is satisfied by all elements present in the array.
  • If one of the conditions is not satisfied then it will return false.
  • It takes one callback and returns a boolean if the condition is satisfied.
  • UseCase: check if all students cleared the fees or not.
students.every((student) => {
    return students.fee == 0
  })

// false
Enter fullscreen mode Exit fullscreen mode

some()

  • Return true, if the condition is satisfied by a minimum of one element present in the array.
  • It takes one callback and returns a boolean if the condition is satisfied.
  • UseCase: check if all students cleared the fees or not.
students.some((students) => {
    return students.fee == 0
  })

// true
Enter fullscreen mode Exit fullscreen mode

findIndex()

  • It returns the first index of an element that satisfies the condition.
  • It takes one callback and checks to try to satisfy the condition, if the condition is satisfied then it returns the index of that element.
  • UseCase: find the index of the student who has ranked one.
students.findIndex((students) => {
    return students.rank == 1
  })

// 0
Enter fullscreen mode Exit fullscreen mode

concat()

  • It returns a concatenate/joined array.
  • It is an immutable array method.
const a = [10, 20]
const b = [30, 40]

const c = a.concat(b)

// [ 10, 20, 30, 40 ]
Enter fullscreen mode Exit fullscreen mode
  • In the case of an array you can't contact arrays with a + operator like string. If you try it will return 10,2030,40.

entries()

  • It returns an array that contains a key-value pair in the form of an array([[key, value], [key, value]]).
  • key as index 0 and value as index 1 in the inner array.
  • UseCase: Make an Object iterable.
const obj = { a: 10, b: 20, c: 30, d: 40 };

console.log(Object.entries(obj));
// [ [ 'a', 10 ], [ 'b', 20 ], [ 'c', 30 ], [ 'd', 40 ] ]
Enter fullscreen mode Exit fullscreen mode

keys()

  • It returns an array of keys present in an object.
  • UseCase: at the time of converting object keys to React elements.
Object.keys(obj)
// [ 'a', 'b', 'c', 'd' ]
Enter fullscreen mode Exit fullscreen mode

values()

  • It returns an array of values present in an object.
  • UseCase: at the time of converting an object values to React elements.
Object.values(obj)
// [ 10, 20, 30, 40 ]
Enter fullscreen mode Exit fullscreen mode

assign()

  • It returns one concerted object.
  • UseCase: at the time of the shallow copy.
const source = { a: 10, b: 20 }
const target1 = { b: 30, c: 40 }
const target2 = { c: 50, d: 60}

console.log(Object.assign(source, target1, target2));
// { a: 10, b: 30, c: 50, d: 60 }
Enter fullscreen mode Exit fullscreen mode

JSON.parse() & JSON.stingify()

  • It converts JSON string to Object or Object to JSON String
  • UseCase: Converting API response to usable data.

Correct me if I am wrong!!!

Linkedin | Twitter | GitHub

Top comments (32)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Your map example is poor as it is modifying the content of the original array... something that map is designed to help you avoid. It may confuse people into believing the the original array is always modified.

Collapse
 
milanx profile image
Milan Mohapatra

Check out the new modifications. Thanks

Collapse
 
milanx profile image
Milan Mohapatra

No, it might looks like muteble but but will change it. Thankyou

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Believe me, it definitely will. Run the code, then check the original array. I guarantee it will have changed.

To do what your example's introduction describes, you need to do something like this - which will leave the original array untouched:

students.map(({fee, ...student}) => ({...student, fee: fee-100})) 
Enter fullscreen mode Exit fullscreen mode

Or if you prefer something closer to your original:

students.map(student => {
  const newStudent = {...student}
  newStudent .fee -= 100
  return newStudent 
})
Enter fullscreen mode Exit fullscreen mode

In your example, the newly created array contains the same objects as the original array, and you have modified those. To leave the original array untouched, you need to make copies of the student objects and work on those.

Thread Thread
 
tracygjg profile image
Tracy Gilmore

Hi Milan, In addition to Jon's comment, the second point you made is not quite correct. Instead of "Return the array with the same number of elements present.", it would be more accurate to state "Returns a new array with the same number of elements as the original." but this is not being demonstrated by your example.

To confirm this, you could check what is returned by the map operation against the original array (after performing the operation).

const studentsWithReducedFee = students.map(({fee, ...student}) => ({...student, fee: fee-100}));

console.table(students);
console.table(studentsWithReducedFee);
Enter fullscreen mode Exit fullscreen mode

Sorry to be picky but I also think you mean "transform" rather than "transfer" in your points about map.

Thread Thread
 
milanx profile image
Milan Mohapatra

Thanks for commenting, love to unlearn and learn the correct way.

Thread Thread
 
milanx profile image
Milan Mohapatra

check out the new modifications. thanks

Thread Thread
 
tracygjg profile image
Tracy Gilmore • Edited

Hi Milan, The example is far more representative of a typical use case. I still think the first two bullet points are not quite right and the following might be better:

  • To transform the elements of the input array to produce a new array.
  • Returns a new array...

The reduce example needs a little work and should present the return value.

const totalFees = students.reduce((acc, next) => acc += next.fee, 0);
Enter fullscreen mode Exit fullscreen mode

Please accept my comments in the spirit of friendship and knowledge sharing.

Collapse
 
dsaga profile image
Dusan Petkovic

I think its fine if content like this already exists on dev.to already, from my perspective dev.to is more about opening discussions on some topics and also for people to offer feedback to content creators and also help them improve, so this is a good start!

Collapse
 
milanx profile image
Milan Mohapatra

Thanks @dsaga

Collapse
 
devgancode profile image
Ganesh Patil

Agree!
Array methods are essentials.

Collapse
 
milanx profile image
Milan Mohapatra

Agree too.

Collapse
 
joolsmcfly profile image
Julien Dephix • Edited

Hi!

Array methods FTW!

You can shorten your code a tad more:

students.find((student) => {
    return student.rank == 5;
  })
Enter fullscreen mode Exit fullscreen mode

becomes (notice strict comparison as well)

students.find((student) => student.rank === 5)
Enter fullscreen mode Exit fullscreen mode

Your reduce example becomes:

students.reduce((acc, next) => acc + next.fee, 0)
Enter fullscreen mode Exit fullscreen mode

Also, under entries you wrote :

return a 2D array which is converted to an Object.

What do you mean by converted to an object? Are you referring to Object.fromEntries which creates an object from an array of entries?

And lastly, it'd be more interesting if you showed what students variable holds. It would allow "noobs", to quote you, to play with the code at home.

Full doc on arrays.

Collapse
 
milanx profile image
Milan Mohapatra

Thanks for commenting. I wrote this to make a type of notes of what I studied. I will consider your thoughts on my upcoming notes. check out the correction I made on entries(). Thanks for your time.

Collapse
 
joolsmcfly profile image
Julien Dephix • Edited

Just saw your edit, almost there!

entries does not return an object iterator but an array.

Also:

you can't contact arrays

You probably mean concatenate.

It returns a connected/joined array.

It returns the result of concatenating two arrays.

I'm not being picky, using the right vocabulary helps understanding concepts.

Thread Thread
 
milanx profile image
Milan Mohapatra

Yes agreed, thanks @joolsmcfly

Thread Thread
 
milanx profile image
Milan Mohapatra

It returns iterator in case of Array.

Collapse
 
tsolan profile image
Eugene

Also concat can be replaced with spread operator:
a.concat(b) is the same as […a, …b]

Collapse
 
milanx profile image
Milan Mohapatra

yaa right, thanks

Collapse
 
codingjlu profile image
codingjlu

JSON.stingify() & JSON.stingify()??

Collapse
 
kaamkiya profile image
Kaamkiya

I think the author meant JSON.stringify and JSON.parse (correct me if I'm wrong)

Collapse
 
milanx profile image
Milan Mohapatra

yes thanks.

Collapse
 
milanx profile image
Milan Mohapatra

yaa, I forgot. Thank you for reminding me.

Collapse
 
kwang profile image
Henry

Good!

Collapse
 
milanx profile image
Milan Mohapatra

Thanks Henry

Collapse
 
softmantk profile image
NIKHIL CM

I think people need to stop posting the same stuff with different titles. There are way too many articles about arrays and how they work.

Collapse
 
milanx profile image
Milan Mohapatra

Thanks, @softmantk for your time, I write this as my notes. Whatever I am studying I am trying to make notes like articles.

Collapse
 
manchicken profile image
Mike Stemle

I feel like the MDN documentation does a better job of explaining these, and does so without the unkind clickbait title.

Collapse
 
milanx profile image
Milan Mohapatra

Thank you for your time, I will try my best in my upcoming notes.

Collapse
 
gregjacobs profile image
Greg

*JSON.stringify()

Collapse
 
mythilisundarajan profile image
mythiliSundarajan

super

Collapse
 
milanx profile image
Milan Mohapatra