DEV Community

AmnaAbd
AmnaAbd

Posted on

javascript-tricks

Arrays

Union of arrays

let a = [1, 2, 3, 4, 5];
let b = [3, 4, 5, 6, 7];

let result = [...new Set([...a, ...b])]; // [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

Intersection of arrays

let a = [1, 2, 3, 4, 5];
let b = [2, 3, 4, 6];

let result = a.filter(val => ~b.indexOf(val)); // [2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Get non intersected values

let a = [1, 2, 3, 4, 5];
let b = [2, 3, 4, 6];

let result = a.filter(val => !~b.indexOf(val)); // [1, 5]
Enter fullscreen mode Exit fullscreen mode

Printing array of array values in a new line

const a = [
  [11],
  [7, 15],
  [5, 9, 13, 20],
  [3, 6, 8, 10, 12, 14, 18, 25]
];
const result = a.reduce((el, acc) => el + acc.join(' ') + '\n', '\n');

// output
/*
  11
  7 15
  5 9 13 20
  3 6 8 10 12 14 18 25
*/
Enter fullscreen mode Exit fullscreen mode

Removing duplicates from an array


/*
 #method 1
*/

  let fruits = ['banana','mango','apple','sugarcane','mango','apple']

  let uniqueFruits = Array.from(new Set(fruits));

 // uniqueFruits -- [ 'banana', 'manago', 'apple', 'sugarcane' ]

/*
 # method 2
*/

  let uniqueFruits2 = [...new Set(fruits)];

  // uniqueFruits2 -- [ 'banana', 'manago', 'apple', 'sugarcane' ]

Enter fullscreen mode Exit fullscreen mode

Replace the specific value in an array

    var fruits2 = [...fruits];

    fruits2.splice(0,2,"potato","tomato");

    // fruits2  ['potato', 'tomato', 'apple', 'sugarcane', 'manago', 'apple' ]

Enter fullscreen mode Exit fullscreen mode

Mapping array without maps


  let friends = [
      {name:"John", age:22},
      {name:"Peter", age:23},
      {name:"bimbo",age:34},
      {name:"mark",age:45},
      {name:"Esther",age:21},
      {name:"Monica",age:19}
  ];

  let friendNames = Array.from(friends,({name})=>name);

  // friendNames --   ['John', 'Peter', 'bimbo', 'mark', 'Esther', 'Monica' ]



Enter fullscreen mode Exit fullscreen mode

Emptying an array

  let fruits = ['banana','mango','apple','sugarcane','mango','apple']

  fruits.length = 0;

  // fruits -- []
Enter fullscreen mode Exit fullscreen mode

Convert an array to an object

   let fruits = ['banana','manago','apple','sugarcane','manago','apple']

   const fruitsObj = {...fruits};

   //  fruitsObj --  {'0': 'banana','1': 'mango', '2': 'apple','3': 'sugarcane','4': 'mango','5': 'apple'}

Enter fullscreen mode Exit fullscreen mode

### Fulfill array with data

  let newArray = new Array(10).fill("1");

  // newArray -- ['1', '1', '1', '1','1', '1', '1', '1','1', '1']

Enter fullscreen mode Exit fullscreen mode

Merging Arrays

  let fruits = ['banana','manago','apple'];
  let meat = ["Poultry","beef","fish"]
  let vegetables = ["Potato","tomato","cucumber"];
  let food = [...fruits,...meat,...vegetables];

  // food  -- ['banana',  'manago','apple',   'sugarcane','manago',  'apple','Poultry', 'beef','fish',    'Potato','tomato',  'cucumber']

Enter fullscreen mode Exit fullscreen mode

Merging only duplicates value in two arrays

    let numOne = [0,2,4,6,8,8];
    let numTwo = [1,2,3,4,5,6];

    const duplicatedValue = [...new Set(numOne)].filter(item=>numTwo.includes(item));
    // duplicatedValue -- [ 2, 4, 6 ]

Enter fullscreen mode Exit fullscreen mode

Remove falsy value from an array.

    const mixedArray = [0,"blue","",NaN,true,undefined,"white",false];
    const filteredArray = mixedArray.filter(Boolean);

    // filteredArray -- [ 'blue', true, 'white' ]

Enter fullscreen mode Exit fullscreen mode

Reverse an array

  const colors = ['blue','red','green','black'];

  const reverseColors = colors.reverse();
  // reverseColors  -- [ 'black', 'green', 'red', 'blue' ]

Enter fullscreen mode Exit fullscreen mode

Sum of the value in an array

  const val = [1,4,5,7];

  const valSum = val.reduce((x,y)=>x+y);

  // valSum --  17
Enter fullscreen mode Exit fullscreen mode

Generate an array from a function Arguments

 function f() {
    return Array.from(arguments);
  }
  f(1,2,4))

  // result -- [1,2,4]

Enter fullscreen mode Exit fullscreen mode

Strings

Reverse a string

let str = str.split('').reverse().join('');
Enter fullscreen mode Exit fullscreen mode

Replace a character at a particular index

function replaceAt(str, i, char) {
  return s.substring(0, i) + char + str.substring(i + 1);
}
Enter fullscreen mode Exit fullscreen mode

Remove last character in a string


javascript

// using substring
str.substring(0, str.length - 1);

// using slice
str.slice(0, -1)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)