10 Magic of JavaScript String and Array

Badhan Chandra Barman
2 min readMay 5, 2021

1) Always we use the toUpperCase() or, toLowerCase() method to convert a string into capital or smaller letter. But, if we need to convert only the first letter into the capital letter, we need to use:-

const name = ‘badhan’;console.log(name[0].toUpperCase() + name.substr(1, name.length));or,newName = name[0].toUpperCase() + name.substr(1, name.length);console.log(newName);

2) To check whether a word is present or, not,

const sentence = ‘The quick brown fox jumps over the lazy dog’;console.log(sentence.includes(cat)); //falseconsole.log(sentence.includes(dog)); //true

3) To remove Unnessacery white space of any user input,

const input = ‘ This is JS Magic ’;console.log(input.trim()); //This is JS Magic

4) Easy Way to concate two string

const str1 = ‘Hello’;const str2 = ‘World’;console.log(str1.concate(‘ ’ ’, str2));Easy Way: console.log(str1 + ‘ ‘ ’ + str2);

5) Delete a specific element from an array in JavaScript Array:

const name = [ Badhan, Aakash, KKK, Puja, Chalantica ];name.splice( name.indexOf(‘KKK’), 1 );console.log(name);

6) Clear concept about split(), slice() and replace :-

split() can convert a string into an array of sub-stringconst sentence = ‘The quick brown fox jumps over the lazy dog’;const arr = sentence.split(‘ ’);console.log(arr);output: [ ‘The’, ‘quick’, ‘brown’, ‘fox’, ‘jumps’, ‘over’, ‘the’, ‘lazy’, ‘dog’ ]

7) Remove an object from an array of object

const salaryList = [ { name: ‘Jhon’, salary: 12 }, { name: ‘kay’, salary: 13 },{ name: ‘Sunny’, salary: 15 } ];const index = salaryList.findIndex(s => s.salary === 13);salaryList.splice(index, 1);or, salaryList.splice(index, index ≥ 0 ? 1 : 0);

8) Easy way to remove an object from an array of the object using filter

const salaryList = [ { name: ‘Jhon’, salary: 12 }, { name: ‘kay’, salary: 13 },{ name: ‘Sunny’, salary: 15 } ];salaryList = salaryList.filter(s => s.salary !== 13);

9) Easy way to calculate total from an array of object

const total = salaryList.reduce((total, s) => total + s.salary , 0);arrayOfObject.reduce((variableName, singleObject) => returningValue, initialValue)

10) Array methods to makes your life easier

array.map() -> return every element from an array;

array.find() -> return first element by it’s condition

array.filter -> return multiple element by condition

--

--