JS snippets in working with strings

JS snippets in working with strings

Algorithm for method selection when working with arrays

With the help of the following snippet written by Sarah Drasner, we arrive at the appropriate method using a simple algorithm:

See the Pen Array Explorer by Web programming (@chos) on CodePen.


Is the input a string?

The data type checking problem is based on the fact that when using the toString() method, the array is cast to the following string: “[object Array]”.

Refining array elements

The following snippet shows a function that eliminates “unwanted” string members: null, “”, false, undefined, and NaN.

Differences in two strings

The solution shown in the following snippet finds all members of an array that are not in both arrays.

Delete duplicate values in an array

a) Array of primitives

Casting an array into a temporary object (array values into object keys), then iterating through the object keys with the in operator:

This approach doesn’t preserve order and doesn’t distinguish number from “number” (1 == “1”)

The filter() method is used here, which takes a callback function as an argument. The callback function tests each member of the array (according to some condition), and if the condition is met, it inserts (returns) the element into the new array. Three parameters currentValue, index, string of Duplicates are automatically passed to the callback function.
In our condition, the function indexOf() is used, which searches the array and finds the index member of the array based on its value. If the array index obtained using the method nizDuplicata.indexOf(currentValue) matches the current index, it means that there was no such value. If there are two identical values ​​in the sequence, when searching with the methodindexOf() the first value will “pass” the condition, while the second will not because it will return the index of the first value, which will not match the current index.

Set is a new type of data collection that appeared with ES6. The main feature of this collection is that it contains only unique values in the collection.

Procedure:
First, a set object is created that has unique values, then with for..of iteration through the set object, a sequence is created. This process could be “shortened” by using the ES6 method from() which creates an array:

b) Array of objects

Unlike primitives which are stored by value, objects are stored by reference, so the previous approaches will not give good results.

To find duplicate arrays, we will use the method filter() which creates a new array from array elements that passed some test and returned TRUE. When populating a helper object with key/value pairs, each key is converted to a string, so we cannot distinguish the number 1 from the string “1”. But using the expression JSON.stringify(el) allows us to distinguish them anyway. This expression returns different values depending on the type, as shown in the following example:

Joining two strings

Merging two strings (with duplicates)

Concatenating two strings into a new string with the concat() method generates a new string. However, this method is not good for large arrays because it consumes resources by creating a new array.

The push() method does not generate a new string, so it is more economical in terms of resources compared to the concat() method, so this method is recommended in the case of working with large strings. However, this method has a limitation, the array being added (in this case array2) cannot have more members than the maximum number of parameters that the function can receive (Chrome33: 65535, Firefox27:262143, IE11: 131071, Opera12: 1048576).

or

Note: See here why the apply() method is used in the previous expressions.

Concatenating two strings is easy using the spread operator:

Merging two strings (no duplicates)

Clone string

If we want to create a new string that will occupy a new place in memory and contain a copy of the current string, we will use the following snippet:

Getting the last members of an array

The last members of the array are obtained using the slice() method but with a negative argument -1:

Finding an array member by value

In the following snippet, the method indexOf() is used, which returns the index of the requested element found in the array or returns the value -1 if the array does not contain it. If two attributes are used in the indexOf() method, then the second attribute defines from which index to start the search.

Example

Remove a specified string member

Remove a specific member of an array selected by member value:

Emptying array

With this method, it should be noted that this way deletes the contents of the memory to which the reference of that variable points, so if there is another variable that has the same reference to that part of the memory, it will also be changed.

We use this method if we want to delete the members of the array but not to delete the reference. The expression “string=[]” assigns a new empty string to the variable and does not affect other references. It should be noted that this method consumes memory because the memory location where the old array was stored is still occupied by the old array data.

Sorting

Sorting an array of strings

Sorting list

See the Pen JS sort list by Web programming (@chos) on CodePen.


See the Pen Sorting a jQuery list by Web Programming (@chos) on CodePen.


Sorting an array of numbers

The sort() method is initially intended to sort an array of strings, therefore when sorting an array of numbers it gives wrong results.

Solution

For use with numbers, you need to add a comparison function.

js sort algorithm

js sort algorithm
js sort algorithm

js sort algorithm

js sort algorithm
js sort algorithm

js sort algorithm

Max and min string

The smallest member of the array

ES5 mode

ES6 – spread operator

ES6 – Spread operator + arrow function

or even more clearly written with the arrow function:

The largest member of the array

Sum of array

Average string member

Mixing the order of array elements

The sort() method takes as a parameter a callback function that “comparison function” (or negative number or zero or positive number), the sort() method knows which number is larger and which is smaller. Therefore, if we screw up the sort() method and return random results, it will also return randomly mixed array numbers.

This method uses the Fisher–Yates algorithm:

Extracting a random string member

Switching string to list of elements

Some built-in features in theJavaScript for example Math.max() do not accept a string as an argument but a list. Therefore, there is a need to transform a string into a list, and we can do it in the following ways:

The apply() function can accept a string as an argument, so although that is not its main purpose, it is often used to “convert” a string to a list of arguments. The first argument to the apply() function must be the object pointed to by the this keyword (this is the primary purpose of the apply function), and the second is a string passed to the callback function as an argument list.

Example

In the following example, the Math object function accepts only a list of arguments (not an array), so apply() is used before it:

Example

The push() method needs to be passed a list of elements in the form of arguments, as in the following example:.

However, if we want to pass the whole array, we need to pass it as a list, and for that we will use the apply() method which expects a list as the second argument, so it will implicitly transfer the array to the list:

This method requires the use of the ES6 spread operator: