My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
A Few Tips in Javascript

Photo by JESHOOTS.COM on Unsplash

A Few Tips in Javascript

Sometimes it is possible to look for more beautiful solutions in JavaScript I hope this article attracts your attention

MohammadReza Khorrami's photo
MohammadReza Khorrami
·Jan 6, 2022·

5 min read

String Reverse

Well, in order to invert a string, we need to know that a string in JavaScript itself is an array.

const stringReverse = (str) => {
    return str[0];
}

console.log(stringReverse('string reverse!'));

In the following example, you can see the output answer of the above example, which returns the first index of the string Indicates that our string is an array.

Screenshot from 2022-01-05 22-36-39.png

Via split() method could return our string to an array.

const stringReverse = (str) => {
    return str.split('');
}

console.log(stringReverse('string reverse!'));

The output is as follows.

Screenshot from 2022-01-05 22-59-12.png

Even space are indexed in the array, Now with the reverse() method in the array we can reverse our array.

const stringReverse = (str) => {
    return str.split('').reverse();
}

console.log(stringReverse('string reverse!'));

The output is as follows.

Screenshot from 2022-01-05 23-19-19.png

The join function can now complete the array and connect all the characters.

const stringReverse = (str) => {
    return str.split('').reverse();
}

console.log(stringReverse('string reverse!'));

The output is as follows.

Screenshot from 2022-01-05 23-32-17.png

You can also use the map method in the array to get the above answer.

const stringReverse = (str) => {
    return str.split('').map((val) => {
        return val;
    }).reverse().join('');
}

console.log(stringReverse('string reverse!'));

Integer Reverse

In order to invert a number, we must also pay attention to negative numbers Well, first we go to the inverse of positive numbers.

const IntegerReverse = (num) => {
    return num;
}

console.log(IntegerReverse(123))

In the example above, if we show the output of 123, it is a number.

Screenshot from 2022-01-06 10-54-10.png

In the image above, we can convert a number to a string by the toString() method. Now we can convert this string to an array and vice versa. This array is as follows:

const IntegerReverse = (num) => {
    return num.toString('').reverse().join('');
}

console.log(IntegerReverse(123))

The output of the example above is as follows.

Screenshot from 2022-01-06 11-04-57.png

Well, to invert a negative number with a sign, we can use the Math.sign() function in this case as follows.

const IntegerReverse = (num) => {
    const reversed num.toString('').reverse().join('');
    return reversed * Math.sign(num);
}

console.log(IntegerReverse(-321))

But the output of the above example is as follows: Not a Number.

Screenshot from 2022-01-06 11-31-36.png

This is because the left sign of the number moves to the right when reversing, To solve this problem you can use the parseInt() function as follows.

const IntegerReverse = (num) => {
    const reversed num.toString('').reverse().join('');
    return parseInt(reversed) * Math.sign(num);
}

console.log(IntegerReverse(-321))

The output of the example above is as we expected.

Screenshot from 2022-01-06 11-43-50.png

Single Number

We can use the Xor operator to return an element in the array that is not duplicate, The Xor operator compares two operands if the result is false, otherwise the result is true.

const SingleNumber = (arr) => {
    let result = 0;

    for (let i = 0;  i < arr.length; i++) {
          result ^= arr[i];
    }
    return result;
}

console.log(SingleNumber([2, 2, 1]));
console.log(SingleNumber([4, 2, 1, 2, 1]));

In the example above, we scroll through the items in the array and check the inequality of the items with the Xor operator, and the answer is returned as follows.

Screenshot from 2022-01-06 12-45-59.png

In the output above you can see that item 1 in the first array and item 4 in the second array are not duplicates, The following method can also be used to navigate the array.

const SingleNumber = (arr) => {
    let result = 0;
    arr.forEach(item => { result ^= item })
    return result;
}

console.log(SingleNumber([2, 2, 1])); // Output: 1
console.log(SingleNumber([4, 1, 2, 1, 2])); // Output: 4

Remove Duplicates

There are three methods for removing duplicate items from the array, which are described below. The first solution is to use the filter() method as follows:

const RemoveDuplicates = (arr) => {
    return arr.filter((value, index) => {
        return arr.indexOf(value) === index;
    })
}

console.log(RemoveDuplicates([1, 1, 2]));
console.log(RemoveDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]));

In the example above, we first filtered the array, then checked it with the indexOf() method. If it was equal to the index, then return the same item, duplicate items will be removed as follows:

Screenshot from 2022-01-06 13-25-10.png

We can also use the new Set as follows with the new ECMAScript.

const RemoveDuplicates = (arr) => (Array.from(new Set(arr)));

console.log(RemoveDuplicates([1, 1, 2]));  // Output: [ 1, 2 ]
console.log(RemoveDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]));  // Output: [ 0, 1, 2, 3, 4 ]

In the example above, we used the Array.form() function to convert the output to an array. We can also have the same output as the following.

const RemoveDuplicates = (arr) => ([...new Set(arr)]);

console.log(RemoveDuplicates([1, 1, 2]));  // Output: [ 1, 2 ]
console.log(RemoveDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]));  // Output: [ 0, 1, 2, 3, 4 ]

In the example above, we used spread syntax es6 to convert our output to an array.

Contains Duplicate

To check if our array contains a duplicate value, we can first obtain the size of the array by Set.size and check if it is equal to the length of our array or not.

const ContainsDuplicate = (arr) => ((new Set(arr)).size !== arr.length);

console.log(containsDuplicate([1, 2, 3, 1]));
console.log(containsDuplicate([1, 2, 3, 4]));
console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]));

In the example above, if our condition is not equal to false, otherwise true, which is shown below.

Screenshot from 2022-01-06 14-06-07.png

There is also another method as follows, but my personal opinion is that it is complicated, first we created an empty object and assigned it to a variable, then we looped it inside the array and put it in the condition loop to check if our items are duplicate or not, which you can see below.

const ContainsDuplicate = (arr) => {
    let newvalue = {};
    for (let i = 0; i < arr.length; i++) {
        if(arr[i] in newvalue) {
            return true;
        }
        newvalue[arr[i]] = true;
    }
    return false;
}

console.log(containsDuplicate([1, 2, 3, 1]));
console.log(containsDuplicate([1, 2, 3, 4]));
console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]));

I hope you use this article, thank you for your attention.