Simple Tricks to Manipulate Data in JavaScript
Manipulating data is crucial to software engineering. Whether it’s transforming strings to numbers, or arrays to objects, one usually finds themselves working with one data set and needing to change it someway, somehow.
The simplest way can sometimes be the best way, especially when it comes to algorithms. Given time complexity the less your program needs to do the better. Here are a few tricks to make it easier.
Strings. I love strings. They tend not to lend themselves to math problems, which is always a plus for those who aren’t up to speed on advanced math. The most common thing one might need to do is turn said string into an array. Good news! A string is an array in JS… sort of. You can iterate through strings which can solve simple problems, but what if you need an index? Then you need an array, and .split() is here to help, as it will split on any character or space or lack thereof, and immediately transform the string. Need a number from a string? Well you can’t just turn any string into a number. “Bologna” is not a number, but “12” is, and if you put a + sign in front of it JS says “hey that’s no string its 12 the number”.
Numbers. They don’t usually change. I mean what’s a number besides, well, a number. If you need to change a number say into a string just put some quotes around it. That was easy, but it does come in handy. Need the largest single digit in a number like 145356663437191? Convert it to a string, split it, sort it and return.
Arrays. Arrays are one of the most useful data structures in all of programming. They’re very basic, and therefore lend themselves to all kind of simple data storage. Sometimes you need an array from a few different arrays. Just use .concat(). Sometimes, however, you may need to transfer array values to an object. Just create a new object, iterate through the array, and store the array values at a key in the new array. This comes in handy if you need a counter to see how many times a value occurs.
Objects. Objects are a little more complicated, but some key (object humor) information can really come in handy. Enter the Object.keys() and Object.values() methods. They return an array or keys or values. Need both the keys and values? Use Object.entries() to get an array of the key values pairs in their own little arrays.
There are many, so many more ways to manipulate data is JavaScript. The best way to find out how is to try it out yourself!