Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

June 1, 2023

4 Type of Techniques to Remove Duplicates from Arrays in JavaScript

 

Efficient Ways to Remove Duplicates from an Array in JavaScript

JavaScript array duplicates | Remove duplicates from arrays | Efficient JavaScript array operations | JavaScript array manipulation | Set data structure in JavaScript | Filter method for array | manipulation | Reduce method for removing duplicates | JavaScript spread operator for array operations | Improve code efficiency with duplicate removal | Preserve array order while removing duplicates

Introduction:

4 Type of Techniques to Remove Duplicates from Arrays in JavaScript: Working with arrays is a common task in JavaScript development, and at times, you may encounter the need to remove duplicate elements from an array. Duplicates can adversely affect the efficiency and correctness of your code, so it's essential to know effective ways to eliminate them. In this article, we will explore different techniques to remove duplicates from an array in JavaScript, highlighting their pros and cons.

1. Using the Set Data Structure:

JavaScript provides a built-in data structure called Set, introduced in ECMAScript 2015 (ES6), which automatically removes duplicates. Here's how you can use it:

Eg: const arrayWithDuplicates = [1, 2, 3, 4, 1, 2, 5];
const uniqueArray = Array.from(new Set(arrayWithDuplicates));
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

The Set data structure only allows unique values, making it a convenient option for removing duplicates. However, it converts the array to a Set and then back to an array, potentially altering the order of elements.


 2. Using the filter() Method:

The filter() method creates a new array containing elements that pass a specific condition. By combining the filter() method with indexOf(), you can remove duplicates from an array.

Eg: const arrayWithDuplicates = [1, 2, 3, 4, 1, 2, 5];
const uniqueArray = arrayWithDuplicates.filter((value, index) => {
  return arrayWithDuplicates.indexOf(value) === index;
});
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

This approach retains the order of elements in the original array while removing duplicates. However, it has a higher time complexity since it searches for the index of each element in the array repeatedly.


3. Using the reduce() Method:

The reduce() method applies a function to an accumulator and each element in the array, resulting in a single value. By leveraging reduce(), you can construct a new array that only includes unique elements.

 Eg: const arrayWithDuplicates = [1, 2, 3, 4, 1, 2, 5];

const uniqueArray = arrayWithDuplicates.reduce((accumulator, currentValue) => {

  if (!accumulator.includes(currentValue)) {

    accumulator.push(currentValue);

  }

  return accumulator;

}, []);

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

 The reduce() method iterates over the array once, comparing each element to the accumulator array. This approach preserves the order of elements and removes duplicates efficiently.


4. Using ES6 Spread Operator and Set:

ES6 introduces the spread operator, which allows expanding an iterable (like an array) into individual elements. By combining it with the Set data structure, you can remove duplicates concisely.

Eg: const arrayWithDuplicates = [1, 2, 3, 4, 1, 2, 5];

const uniqueArray = [...new Set(arrayWithDuplicates)];

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

This method is concise, efficient, and retains the original order of elements. However, it may not work as expected in older browsers that lack ES6 support.

Techniques to remove duplicates from arrays in JavaScript. Methods like using the Set data structure, filter(), reduce(), and the spread operator.

Enjoy! 

April 19, 2023

How can I convert an image into Base64 string using JavaScript?

In today's world of web development, working with images is an essential aspect of building a dynamic and visually appealing website. However, when it comes to sending images over a network, they need to be converted into a format that can be transmitted easily, such as Base64 strings. In this article, we will discuss how to convert an image into a Base64 string using JavaScript.

What is Base64 encoding?

Base64 is a double to message encoding plan that addresses twofold information in an ASCII string design. This encoding system is commonly used to transfer data over the internet because it can be easily transmitted using email or HTTP POST transactions. The encoded data can also be easily read by both humans and machines.

Base64 encoding works by dividing a stream of data into 6-bit blocks and then mapping each block to a character in the ASCII table. This results in a string that is composed of only ASCII characters, making it easy to transmit across various systems.

Converting an image to Base64 using JavaScript

Converting an image to a Base64 string using JavaScript is a relatively simple process. To do this, we first need to get the image's data as a binary file, and then we can encode it using the Base64 encoding system.

To get the image data, we can use the FileReader API in JavaScript. The FileReader API provides a way to read the contents of a file asynchronously using the readAsDataURL() method. The method reads the contents of the specified file and returns the data as a Base64-encoded data URL.

Here's the example for how to convert an image to a Base64 string:

const imageFile = document.getElementById("image-file").files[0];

// Create a new FileReader object

const reader = new FileReader();

// Read the image file as a data URL

reader.readAsDataURL(imageFile);

// Define a callback function to be called when the file is loaded

reader.onload = function () {

  // Get the Base64-encoded string

  const base64String = reader.result.split(",")[1];

  // Do something with the Base64-encoded string

  console.log(base64String);

};

In the above code, we first get the image file by accessing the input element with the ID "image-file". We then create a new FileReader object and call the readAsDataURL() method, passing in the image file as a parameter. The readAsDataURL() method reads the image file and returns the data as a Base64-encoded data URL.

Conclusion

Switching a picture over completely to a Base64 string utilizing JavaScript is a straightforward and successful method for sending pictures over an organization. By utilizing the FileReader Programming interface and the Base64 encoding framework, we can without much of a stretch proselyte a picture to a configuration that can be sent across different frameworks. We trust that this article has furnished you with a superior comprehension of how to change a picture over completely to a Base64 string utilizing JavaScript.

Enjoy!

March 27, 2023

Introduction about Gulp.js with beginner’s Guide

Introduction about Gulp.js with beginner’s Guide

 

INTRODUCTION

Swallow is an open-source Javascript tool stash and assignment sprinter which is based on Node.js and NPM and utilized for the improvement of tedious and redundant errands. Many modules are accessible for various undertakings You don't need to program everything without anyone else, there are almost 800 modules prepared for Gulp.js. However, significantly more, Node.js modules can be utilized to assemble the ideal form and advancement process for your necessities.

WHY GULP JS?

As an Engineer or Website specialist, you will probably require a lot of things to construct a cutting edge site: an improvement server, a preprocessor for your Backtalk, Less, or Pointer documents, mechanization to package your JavaScript, instruments to streamline your code, to pack, gather or move things around. Also, assuming that you change something, you believe your records should refresh naturally, or revive the program. You would rather not do this physically


Introduction about Gulp.js with beginner’s Guide

STEP-1: First we need node js which you can download here. And then run below command on terminal

Node -v

STEP-2: Presently after the Establishment of Nodejs. Introduce Swallow js all around the world similarly. Enter the accompanying order in the order brief or terminal

npm install gulp-cli -g

And then check version version

gulp -v


Installation for Project

To set up your undertaking on your PC, make an envelope called "Site page" for instance. You can likewise make a topic organizer in the event that you're utilizing CMS like Drupal. Then, at that point, introduce a hub project by running the typical order. Make a package.json record in your venture registry by

npm init

- Install the gulp package

npm install --save-dev gulp


- Verify your gulp version

gulp --version


Create a new gulpfile

- Create a file gulpfile.js and add the following code for testing

 function mainTask(cb) {

    // place code here

    cb();

 }

exports.default = mainTask


To run the gulp project run this command directory:

gulp

Setting up Gulp for CSS & JS

npm install sass gulp-sass --save-dev


Advantages

  • Simple to code and comprehend
  • The tremendous speed advantage over some other errand sprinter
  • There are a ton of modules accessible which are easy to utilize and they are intended to do each thing in turn.
  • Performs tedious undertakings over and again, for example, minifying templates, packing pictures, and so on.
  • Assuming that you're utilizing Backtalk, you don't need to import documents. You can straightforwardly make a scss document which will bring into CSS by swallow.
Enjoy!

October 19, 2020

In JavaScript simple script for print specific part of website.

 



- You can easly print any part of webpage means any specific div using javascript,

- Please follow simple below steps for that:

e.g.:

HTML

    <div id="any_id_name">

      <p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.</p>

     </div>

JavaScript

    <script type="text/javascript">

var prtContent = document.getElementById("any_id_name");

var WinPrint = window.open('', '', 'width=500,height=500,scrollbars=0,status=0');

WinPrint.document.write(prtContent.innerHTML);

WinPrint.document.close();

WinPrint.focus();

WinPrint.print();

WinPrint.close();

</script>

Note: Please change width and height as per your requirenment of popup size.

Enjoy!

October 1, 2016

JavaScript localstorage with good example



In javascript using localstorage you can simply save any single OR array value same like work as a PHP session.


There is a simple solution though, and that’s to use local storage.

The good news is to stored any data to computer so when page reload then you can get data back from localstorage.


WHAT IS EXACT MEANING OF LOCAL STORAGE?

  • Local Storage: stores data with no expiration date and this is the one we will be using because we want our to-do’s to stay on the page for as long as possible.
  • Session Storage: only saves the data for one session so if the user closes the tab and reopens it all their data will be gone.

BELOW ARE SOME EXAMPLE FOR SET VALUE, GET VALUE AND CLEAR VALUE FROM LOCAL STORAGE

To set item into local storage:

localStorage.setItem('username', 'admin');

To get value from local storage:
localStorage.getItem('username');
Output: admin

To clear any value from local storage:
localStorage.removeItem('username');


Enjoy!





August 16, 2015

javascript validation for radio button in php.

<input type='radio' class='w1' name='w1' value='1'>1<br>
<input type='radio' class='w1' name='w1' value='2'>2<br>
<input type='radio' class='w1' name='w1' value='3'>3<br>

<script>
if ( $(':radio[class=w1]').attr('checked') != 'checked' ) {
    alert('Radio not checked');
}
</script>

Enjoy!

July 28, 2015

How to open a browse any file dialog when click on link using javascript?

- Is there any way to open browse file window open when I click on any <a href> link? Please help me for that I have issue in a site and I want some help!

June 21, 2015

jquery password validation with at least 8 characters, 1 number, 1 upper and 1 lowercase.


Regular expression offers an extremely powerful way of validation for forms password.

I guess your regular expression should look like:


<form id="register">
    <label for="password">Password:</label>
    <input name="password" id="password" type="password"/>
    <span id="result"></span>
</form>

Here is some javascript/jquery code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#password').keyup(function(){
$('#result').html(checkStrength($('#password').val()))
});

function checkStrength(password)
{
//initial strength
var strength1 = 0;
var strength2 = 0;
var strength3 = 0;
var strength4 = 0;

//length is ok, lets continue.
//if length is 8 characters or more, increase strength value
if (password.length < 8) strength1 = 1;
//if password contains both lower and uppercase characters, increase strength value
if (!password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  strength2 = 1;
//if it has numbers and characters, increase strength value
if (!password.match(/([0-9])/))  strength3 = 1;
//if it has one special character, increase strength value
if (!password.match(/([!,%,&,@,#,$,^,*,?,_,~])/))  strength4 += 1
//if it has two special characters, increase strength value
//if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,",%,&,@,#,$,^,*,?,_,~])/)) strength += 1
//now we have calculated strength value, we can return messages
//if value is less than 2

if(strength1==1)
{
$('#result').text('Password too short.');
} else if(strength2==1) {
$('#result').text('Please used upper & lower case letter.');
} else if(strength3==1) {
$('#result').text('Please used number.');
} else if(strength4==1) {
$('#result').text('Please used any special character.');
} else {
$('#result').text('Strong!');
}
}
});
</script>

Enjoy!

June 17, 2015

Javascript validation for radio button.

First write HTML with form and multiple radio fields with same name,

Assign different value for each radio. See in below example.

Also set the form name OR id and form on submit call a function, Below is full example:


<form name="frmAdd" id="frmAdd" onsubmit="return chkRegEvent()" >
  <input type="radio" name="filter" id="filter" value="all" /> View All Evemts
  <input type="radio" name="filter" id="filter" value="upcoming" /> Upcoming Events Only
</form>

In below script check radio button checked OR not?


<script>
function chkRegEvent()
{
    var temp=0;
    for(var i=0; i< document.forms.frmAdd.filter.length;i++)
    {
        if(document.forms.frmAdd.filter[i].checked==true)
        {
            temp=1;
            
        }
        
    }
    if(temp==0)
    {
        alert("Please select filter option.");
        return false;
    }
}
</script>

In alert you should set any message you want.

Enjoy!

The Future of Technology: Emerging Trends to Watch in 2025

Introduction As we navigate through 2025, the technological landscape continues to evolve at an unprecedented pace. Innovations that once se...