Array tit-bits

Β·

1 min read

1. Know it's an array or not

const points = [23, 3, 89, 98, 40]
// Before 😏
console.log(points.length)
// it returns true

// After πŸ‘Œ
console.log(Array.isArray(points))
// it returns true

2. Get last element of an array

const points = [23, 3, 89, 98, 40]
// Before 😏
console.log(points[points.length - 1])
// it returns 40

// After πŸ‘Œ
console.log(points.at(-1))
// it returns 40

3. Count occurrences in an array

const occurencies = (arr) => 
     arr.reduce((a, v) => {
      a[v] = a[v] ? a[v] + 1 : 1;
      return a;
     }, {});

occurencies(['a', 'b', 'a', 'c', 'a',  'a', 'b'])
// {a: 4, b: 2, c: 1}

occurencies([...'soccer'])
// {s: 1, o: 1, c: 2, r: 1}
Β