Header Ads

Header ADS

JS array methods you should know (Part2)

Hey there, let’s continue to know some other useful methods.😁

 



1-Flat():

This method return an one-dimensional array where all sub–arrays element are concatenated into a one.

Let me show you.

const nums = [11,[2,31],-4,[51,6]];

 

const nums2 = nums.flat();

 

console.log(nums2);

 

and the result is:

(6) [11, 2, 31, -4, 51, 6]

2-sort():

we all know what it does 😋! This method sorted a specific array. And the result is within the existing array No need for example here.

3-isArray():

I know it’s kind of weird. but this method return a Boolean value to indicate whether an object is an array or no. you may ask why we use is it?? 😕Well since js use dynamic types you can’t always be confident of variable type. For example in API calls when you store the result in a variable. You don’t want to apply array method before being sure ! Trust me you will get a very annoying bug 😂.

4-Find():

A very useful method to get an element with a specific conditions, the return type is the element type.of course it execute  a function to compare.

const inventory = [

    {name: 'apples'quantity: 2},

    {name: 'cherries'quantity: 8},

    {name: 'bananas'quantity: 0},

    {name: 'cherries'quantity: 5},

    {name: 'cherries'quantity: 15}

    

  ];

  

  const result = inventory.find( ({ name }) => name === 'cherries' );

   console.log(result);

 

And the result is an object : {name: 'cherries', quantity: 8}

 

5-findIndex():

Nearly does the same as the previous one, but the return isn’t an element by its index .so the syntax is the same except the return type!

6-Join():

As you have seen split() , now let’s see join .

It returns the array’s element as a string. By specifying the separator inside it we can customize our result.

const elements = ['Sun', 'Earth', 'Moon'];

 

console.log(elements.join());

// output: "Sun,Earth,Moon"

 

console.log(elements.join(''));

// output: "SunEarthMoon"

 

console.log(elements.join('-'));

// output: "Sun-Earth-Moon"

7-Reverse():

As the name indicates, this method return a reversed array from the existing one.

const nums = [11,2,31,-4,51,6];

 

  

  const result = nums.reverse();

   console.log(result);

And the result for sure : [6, 51, -4, 31, 2, 11]

A very useful case for this method is to reverse a string . know of it a little and try to use ‘split’ and ‘join’ method that we have seen. Don’t jump to the solution fast .😉

 

Solution:

 const str = '!TIoD ym ot emoclew';

 

const res =str.split('').reverse().join('');

 

console.log(res)

 

this is all folks. Hope you like it. wait you want more😮 ? ok see you in part3.😍

Part1

Part3




No comments

Theme images by enot-poloskun. Powered by Blogger.