Javascript group object by its properties

In this small article I will show you how you can easily group the object by its properties.

Below is the function code to group the object by its properties.

Common = {
 	_groupBy:function(list,props) {
		return list.reduce((a, b) => {(a[b[props]] = a[b[props]] || []).push(b);return a;}, {});
	},
}
Here I have this kind of format in my response where the date might be same but not the time. In this example I am going to use the sessionDate properties from the below response screenshot. 

With the below code now I can see new output in response. You can see how with date it is trying to create an array grouping other object with same date.

var sessionData=Common._groupBy(response.data.results,'sessionDate');
console.log(sessionData)

Easy angular trick to disable and enable button while input box empty or populate

In this another small article I will show you how you simply enable and disabled the input button while you type. To perform this simple trick we will hide the button, if the input box is empty similarly if the input box is filled with any keyword the button will not be disabled.

To disabled it means the user will not be able to click the button. Now lets jump towards the button and let us see how the angular is going to perform the same.

In your app.component.html or any component you would like to try add the below code.

<input type="text" class="form-control" [(ngModel)]="dynamic_content">
<button class="btn btn-primary" [disabled]="dynamic_content=== ''">Save</button>

You may see the above code there are only two lines. Usually, there are 4 different types of data binding but in the code, we are using two types of data binding.

  • Two-way data binding and
  • One way data binding (here we are using ” Property data binding”)

Also note, in order to use ngModel inside the input element we need to import FormsModule from angular in app.module.ts file

import "FormsModule" from "@angular/forms";

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

So whenever user type something in the input box, the data gets updated to the button’s property binding called [disabled]=”dynamic_content == ” “. So the disabled attribute checks if the dynamic_content variable is empty or filled with text. So it disabled the button if the variable is empty.

Jquery UI autocomplete with API request

Jquery UI autocomplete with API request is one of the recent thing I have done. I am going to share what I have done. In order to start with Jquery UI autocomplete with API request we will use jqueryUI plugin.

	autoComplete: function(input,apiUrl,selectCallback,renderCallback){
		$(input).autocomplete({
		    minLength: 3,
		    delay: 300, // this is in milliseconds
		    json: true,
		      source:function(request,response){
			        var $this = $(this);
			        var $element = $(this.element);
			        var previous_request = $element.data( "jqXHR" );
			        if( previous_request ) {
			            previous_request.abort();
			        }
			        $element.data( "jqXHR", $.ajax({
								  url:apiUrl,
								  method:"GET",
								  dataType: "json",
								  data: {callData:{text: request.term}},
								  success: function(responseData){
									response(responseData.data.results);
									$(input).removeClass("ui-autocomplete-loading");
								}
					}));
			 },
		      select:selectCallback,
			  create: function() {
			         $(this).data('ui-autocomplete')._renderItem = renderCallback
			     }
		 });
	},

The above function is a object based function also called as method. A method is the function which is associated with an object. You can simply see that I have used the existing autocomplete code from jQuery UI and add some customization. I have also add the feature to cancel the previous API request and give priority to call only the latest. So, if the user keep typing in the text box with 300 ms gap and after 3 words, it will start executing API for each word enter. So, the abort() function is going to handle such request. It will simply cancelled all the previous request.

	var app = {
	createApiPath : function(apiController, apiAction) {
		var jsonUrl = jsonAPIUrl + 'api/' + apiController + '/' +  apiAction + '/';
		return jsonUrl;
	},
	apiCustomPost: function (apiController, apiAction, callParams, callback) {
		$.ajax({
				url: this.createApiPath(apiController, apiAction),
				method: "post",
				data:{
						callData: JSON.parse(JSON.stringify(callParams)),
						api_version: 1,
						deviceType: 'web'
					},
				async: true,
				dataType: "json",
				success: callback,
				error: function (xhr, ajaxOptions, thrownError) {
			}
		});
	},
}

Do you know the difference between var, let and const?

Hey guys, in this another small article I am going to explain the key difference between var, let and const. Now the question is do you know the difference between var, let and const? ..really? Do you even know what let and const can do to improve your code? If you don’t know there is nothing to worry. I am going to explain to you right here in this article. So let’s begin.

Difference between declaration and initialization.

In order to know the difference between var, let and const, you first need to understand the difference between declaration and initialization.

var a // <---- declaration of variable a
var a = "Hello World!" //<--- Initialization of variable a

In the above code, you see if the variable is just declared and not initialize with a value its called declaration. And if the variable is declared and some value assigned to it, its called initialization.

Easy difference between var and const

With var, we can simply change the value of the variable by initialization again.

var x = 12;
x = 9;
console.log(x) // it will output 9

In the above code we have simply updated the value of x from 12 to 9. This is same with let also. You can re-declare the variable and assign a new value to it but with constant it is not same. See below code.

const y = 13;
y = 12; //TypeError: Assignment to constant variable.
console.log(y)

The above code the console.log will return error since we are trying to re-initiate the value of y. In const type of variable it is not allowed change the value again.

By now you must have clear information about on var and const. Whereas still confused about the difference between var and let. So let’s begin again.

Difference between var and let

The only difference between var and let is of scope difference. let and const have block level of scope whereas var has function level scope. If you don’t know what is scope, there is nothing to worry. I am going to explain that in few example.

function adult(age) {
  if (age > 18) {
    var status = 'adult';
  }
  console.log(status); //adult
}
adult(20);

In the above example the ouput of the adult(20) will be ‘adult’. You can see that the status initialized inside the function and if statement. Whereas it is called outside the block statement called if. Now to let you understand what is block. Any thing inside these two { } parenthesis is called block. Example below might help you to understand.

{
// some code here
// this is block level scope
// if I am let and const I should not be called outside this scope.
}

Now lets move towards the important topic where let is used.

function adult(age) {
  if (age > 18) {
    let status = 'adult';
  }
  console.log(status); //ReferenceError: status is not defined
}
adult(20);

This shows that the status outside the block level scope is not allowed to call.

With the above example, you now must have a clear understanding of the difference between var, let and const.

Remove duplicate array via vanilla JavaScript

In this, another small tutorial I am going to show you how you simply remove the duplicate array from any array given. This is a very simple trick, so you don’t require any other plugin or framework. I am going to show you how to remove duplicate array via vanilla JavaScript only.

Remove duplicate array via vanilla JavaScript easy

var duplicateArray = [1,1,1,5,6,3,2,8,9,5,2,2,4,4];
var cleanArray = [];

In the above array, we have many duplicate numbers we see. Now in order to remove duplicate value from the array, we run a loop. Also, we initialize a new blank array, where we are going to push all the unique items removing duplicate array.

for(var i=0; i<duplicateArray.length; i++){ 
    if(cleanArray.indexOf(duplicateArray[i]) === -1){ 
         cleanArray.push(duplicateArray[i])
    } 
}

The first line for(var i=0; i, simply states that we are inititating for loop for duplicateArray.

The second line if(cleanArray.indexOf(duplicateArray[i]) === -1){ , we are checking if the loop item `duplicateArray[i]` doesn't exist in our new blank array so called cleanArray[]. So if the loop item is not present in the cleanArray[] then we push the loop inside the cleanArray[]. The -1 return when the indexOf() method doesn't find the position of loop value.

In the next third line we simply push the new item filter from the second line to our cleanArray[]

Hope it helps anyone.