Do not operate on arrays only for loops

Posted by iMiles on Thu, 02 Jan 2020 20:37:28 +0100

In many cases, when we operate an array, we often end up with a for loop, ignoring other methods provided by the array. After reading this article, I hope you can change your mind to deal with arrays, and then write more beautiful, concise and functional code.

reduce

Sum of all values in the array

var sum = [0, 1, 2, 3].reduce(function (a, b) {
    return a + b;
}, 0);
// sum is 6

Converting a two-dimensional array to a one-dimensional array

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
    function (a, b) {
        return a.concat(b);
    },
    []
);
// flattened is [0, 1, 2, 3, 4, 5]

Count the number of occurrences of each element in the array

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function (allNames, name) {
    if (name in allNames) {
        allNames[name]++;
    }
    else {
        allNames[name] = 1;
    }
    return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

Bind the array contained in the object array using the extension operator and initialValue

// friends - an array of objects 
// where object field "books" - list of favorite books 
var friends = [{
    name: 'Anna',
    books: ['Bible', 'Harry Potter'],
    age: 21
}, {
    name: 'Bob',
    books: ['War and peace', 'Romeo and Juliet'],
    age: 26
}, {
    name: 'Alice',
    books: ['The Lord of the Rings', 'The Shining'],
    age: 18
}];

// allbooks - list which will contain all friends' books +  
// additional list contained in initialValue
var allbooks = friends.reduce(function (prev, curr) {
    return [...prev, ...curr.books];
}, ['Alphabet']);

// allbooks = [
//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace', 
//   'Romeo and Juliet', 'The Lord of the Rings',
//   'The Shining'
// ]

Array weight removal

var arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
var result = arr.sort().reduce(
    function (init, current) {
        if (init.length === 0 || init[init.length - 1] !== current) {
            init.push(current);
        }
        return init;
    },
    []
);
console.log(result); //[1,2,3,4,5]

Array to integer

var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
    return x * 10 + y;
}); // 13579

map

Find the square root of each element in the array

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// The value of roots is [1, 2, 3], and the value of numbers is still [1, 4, 9]

Formatting objects in an array

var kvArray = [{key: 1, value: 10},
    {key: 2, value: 20},
    {key: 3, value: 30}];

var reformattedArray = kvArray.map(function (obj) {
    var rObj = {};
    rObj[obj.key] = obj.value;
    return rObj;
});

// The reformattedArray array is: [{1: 10}, {2: 20}, {3: 30}], 

// The kvArray array was not modified: 
// [{key: 1, value: 10}, 
//  {key: 2, value: 20}, 
//  {key: 3, value: 30}]

Using a function with only one parameter to map an array of numbers

var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
  return num * 2;
});

// The values of the doubles array are: [2, 8, 18]
// The numbers array has not been modified: [1, 4, 9]

Reverse string

var str = '12345';
Array.prototype.map.call(str, function(x) {
  return x;
}).reverse().join('');

// Output: '54321'
// Bonus: use '===' to test if original string was a palindrome

every

Check the size of all array elements

function isBigEnough(element, index, array) {
    return (element >= 10);
}

var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true

filter

Filter out all small values

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

find

Using the properties of an object to find objects in an array

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) {
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }

Finding prime numbers in an array

function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5

some

Test the value of an array element

function isBigEnough(element, index, array) {
    return (element >= 10);
}

var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true

sort

Ascending sort

var list = [1, 3, 7, 6];

list.sort(function(a, b) {
    return a-b;
});

Descending sort

var list = [1, 3, 7, 6];

list.sort(function(a, b) {
    return b-a;
});

Use mapping to improve sorting

// Array to be sorted
var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];

// Temporary storage of numbers and positions to be sorted
var mapped = list.map(function (el, i) {
    return {index: i, value: el.toLowerCase()};
})

// Sort arrays by multiple values
mapped.sort(function (a, b) {
    return +(a.value > b.value) || +(a.value === b.value) - 1;
});

// Get the result of sorting according to the index
var result = mapped.map(function (el) {
    return list[el.index];
});

Topics: Javascript