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 }
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 }
]
*/
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'
]
*/
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
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
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
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
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 ]
- In the case of an array you can't contact arrays with a
+
operator like string. If you try it will return10,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 ] ]
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' ]
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 ]
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 }
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!!!
Top comments (32)
Your
map
example is poor as it is modifying the content of the original array... something thatmap
is designed to help you avoid. It may confuse people into believing the the original array is always modified.Check out the new modifications. Thanks
No, it might looks like muteble but but will change it. Thankyou
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:
Or if you prefer something closer to your original:
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.
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).Sorry to be picky but I also think you mean "transform" rather than "transfer" in your points about
map
.Thanks for commenting, love to unlearn and learn the correct way.
check out the new modifications. thanks
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:
The
reduce
example needs a little work and should present the return value.Please accept my comments in the spirit of friendship and knowledge sharing.
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!
Thanks @dsaga
Agree!
Array methods are essentials.
Agree too.
Hi!
Array methods FTW!
You can shorten your code a tad more:
becomes (notice strict comparison as well)
Your
reduce
example becomes:Also, under
entries
you wrote :What do you mean by
converted to an object
? Are you referring toObject.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.
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.Just saw your edit, almost there!
entries
does not return an object iterator but an array.Also:
You probably mean
concatenate
.It returns the result of concatenating two arrays.
I'm not being picky, using the right vocabulary helps understanding concepts.
Yes agreed, thanks @joolsmcfly
It returns iterator in case of Array.
Also concat can be replaced with spread operator:
a.concat(b) is the same as […a, …b]
yaa right, thanks
JSON.stingify()
&JSON.stingify()
??I think the author meant
JSON.stringify
andJSON.parse
(correct me if I'm wrong)yes thanks.
yaa, I forgot. Thank you for reminding me.
Good!
Thanks Henry
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.
Thanks, @softmantk for your time, I write this as my notes. Whatever I am studying I am trying to make notes like articles.
I feel like the MDN documentation does a better job of explaining these, and does so without the unkind clickbait title.
Thank you for your time, I will try my best in my upcoming notes.
*JSON.stringify()