JavaScript String – replace() Method

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a Regular Express, and the replacement can be a string or a function to be called for each match.

Replace first occurrence of character
var str = “hello,,”;
str = str.replace(‘,’, “|”);
alert(str);
Output: hello|,

Replace all occurance of character. In example below we will replacing , comma with | pipe
var myStr = “hello,,world”;
myStr = myStr.replace(/,/g, “|”);
alert(myStr);
Output: hello||world,

In the above example, we used the global (g) flag on the regular expression literal to match all occurrences. The i flag is also often useful for a case-insensitive match.

Replace last occurrence of character. In this case we will be replacing last , comma character with | pipe.
var str = ‘Hello,,world’;
str = str.replace(/,([^,]*)$/, ‘|’+’$1’);
alert(str);
Output: hello,|world,

Functional Programming in JavaScript

The Javascript support multiple programming paradigms like object-oriented and functional paradigms. , The most of the javascript libraries are multiple programming paradigms. However, JQuery has a strong flavor of functional programming, while Ext.js is a completely object-oriented javascript library.

In this section, we will be learning most important predefine function in the JavaScript to perform an operation like (map, filter, reduce ) on collection or an array.

Functional programming provides developers with the tools to abstract common collection operations into reusable, composable building blocks.  The most of the operations we perform on collections can be accomplished with five simple functions (some native to JavaScript and some included in the RxJS library):

  1. map
  2. filter
  3. concatAll
  4. reduce
  5. zip

We will be learning the map, filter and reduce functions.

  1. Map: The 
    <strong>map()</strong>

     method creates a new array with the results of calling a provided function on every element in the calling  or existing array. We have to supply array, runs that through a function (which can be used to perform certain operations on the supplied array – such as, for example, converting each array item value to upper case) and subsequently returns a new array once completed.

    var numbers = [1, 4, 6, 10];
    var doubles = numbers.map(function(x) {
       return x * 2;
    });
    // doubles is now [2, 8, 12, 20]
    // numbers is still [1, 4, 6, 10]
    
    //ES6 example
    
    const numbers = [2, 14, 18, 22];
    const halves = numbers.map(x => x / 2);
    // halves is now [1, 7, 9, 11]
    // numbers is still [2, 14, 18, 22]
    
    var numbers = [1, 4, 9];
    var roots = numbers.map(Math.sqrt);
    // roots is now [1, 2, 3]
    // numbers is still [1, 4, 9]

In the second example, we are creating a new array to containing only countries name from existing array as follow.

var newArr = [
{ id: 1, country: "England" },
{ id: 2, country: "Scotland" },
{ id: 3, country: "Wales" },
{ id: 4, country: "Northern Ireland" },
{ id: 5, country: "Republic of Ireland" },
{ id: 6, country: "France" },
{ id: 7, country: "Germany" },
{ id: 8, country: "Italy" },
{ id: 9, country: "Spain" },
{ id: 10, country: "Belgium" },
{ id: 11, country: "Holland" },
{ id: 12, country: "Czech Republic" }
];
// New Array with only countries list
countries = newArr.map(function(x) {
    return x.country
});

console.dir(countries);

 

Filter: The method

filter()

creates a new array with all elements that pass the test implemented by the provided function.

Syntax : var newArray = arr.filter(callback[, thisArg])

When using the map method to create new arrays every value from the original array is mapped to the new array. As useful as this is there are times when you only want to retrieve specific values from an array. Using the filter method values can be retrieved if they meet specific criteria. Let’s take our previous example and use the filter method to only return every 4th item from the associative array:

var newArr = [
{ id: 1, country: "England" },
{ id: 2, country: "Scotland" },
{ id: 3, country: "Wales" },
{ id: 4, country: "Northern Ireland" },
{ id: 5, country: "Republic of Ireland" },
{ id: 6, country: "France" },
{ id: 7, country: "Germany" },
{ id: 8, country: "Italy" },
{ id: 9, country: "Spain" },
{ id: 10, country: "Belgium" },
{ id: 11, country: "Holland" },
{ id: 12, country: "Czech Republic" }
];
var countries = newArr.filter(function(x){
if(x.id % 4 === 0) {
    return x;
}
});
console.dir(countries);

// Outputs following to web console

[{id: 4, country: “Northern Ireland”},
{id: 8, country: “Italy”},
{id: 12, country: “Czech Republic”}]

Second example

const words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];

let longWords = words.filter(word => word.length > 6);

// Filtered array longWords is ["exuberant", "destruction", "present"]

In the third example, we can also combine the filter and map methods for the above examples so we end up with an array populated solely with the names of every 4th company like so:

var existArr = [
{ id: 1, company: "EMC" },
{ id: 2, company: "Google" },
{ id: 3, company: "Facebook" },
{ id: 4, company: "Apple" },
{ id: 5, company: "Infosys" },
{ id: 6, company: "HLC" },
{ id: 7, company: "HP" },
{ id: 8, company: "Wipro" },
{ id: 9, company: "IBM" },
{ id: 10, company: "Paypal" },
{ id: 11, company: "Yahoo" },
{ id: 12, company: "Microsoft" }
],

companies = newArr.filter(function(x){
    if(x.id % 4 === 0){
        return x;
    }
    })
    .map(function(x){
        return x.company
    });
    console.dir(companies);
// Outputs following to web console

[“Apple”, “Wipro”, “Microsoft”]

 

Reduce(): The reduce() method applies a function to an accumulator and each element in the array (from left to right) to reduce it to a single value.   Syntax :

arr.reduce(callback[, initialValue])

The reduce method accepts two parameters; first is the callback function, which is applied to each element of the array, and the second one is the initial value of the accumulator.

The reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: accumulator, currentValue, currentIndex and array. accumulator

The accumulator accumulates the callback’s return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).

The currentValue: The current element being processed in the array.

The currentIndex :  The index of the current element being processed in the array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.

The array:  The array reduce was called upon.

Example one: simple reduce function to calculate the sum of all the array element.

const total = [0, 2, 4, 6].reduce(function(sum, value) {
  return sum + value;
}, 1);
// total is 12


// ES6 version

const total = [0, 2, 4, 6].reduce((sum, value) => sum + value, 1);
// total is 12

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]


// ES6 version
const flattened = [[0, 1], [2, 3], [4, 5]].reduce((a, b) => a.concat(b), []);
// flattened is [0, 1, 2, 3, 4, 5]

 

Example 2: Here we are using most of the callback argument, where html argument is an accumulator, the task is existing an array where we are performing reduce function and index is an index of task array.

class ToDoClass {
    constructor() {
      this.tasks = JSON.parse(localStorage.getItem('TASKS'));
      if(!this.tasks) {
        this.tasks = [
          {task: 'Morning yoga', isComplete: false},
          {task: 'Do Exercise', isComplete: true},
          {task: 'Renew Bank Account', isComplete: false},
        ];
      }
      this.loadTasks();
    }

    loadTasks() {
      localStorage.setItem('TASKS', JSON.stringify(this.tasks));
      let tasksHtml = this.tasks.reduce((html, task, index) => html += this.generateTaskHtml(task, index), '');
      document.getElementById('taskList').innerHTML = tasksHtml;
    }
	
	 generateTaskHtml(task, index) {
      return `
		..............
      `;
	}
}

window.addEventListener("load", () => {
  toDo = new ToDoClass();
});

The JavaScript an Array function

The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects. The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type.

Create an array object
var books = ['C', 'Javascript', 'Java'];

We can easily get number of element in an array object: 
 console.log(books.length); // 3

Looping over an Array we can easily loop the an array element using loop statement.

books.forEach(function(item, index, array) {
console.log(item, index);
});
// C - 0, Javascript - 1, Java -2
Adding new element at the end of an Array

var newLength = books.push('C++');

 

2. push(): Adds one or more elements to the end of an array and returns the new length of the array.

3. splice() method:

The splice() method adds/removes items to/from an array, and returns the removed item(s) and change the content of an array, adding new elements while removing old elements. Splice method adds new element to existing an array and remove an element from to existing array and then add the removed element to new an array.

Syntax
array.splice(index, howMany, [item1][, …, itemN]);

Where index − Index at which to start changing the array.  howMany − total number of old array elements to remove. If howMany is 0, no elements are removed.  item1, …, itemN − Optional, and the elements to be added to the array. If you don’t specify any elements, splice simply removes the elements from the array. 

Note: This method changes the original array.

<body>
<p>Click the button to add and remove elements.</p>
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var companies = ["Apple", "Google", "Facebook", "IBM"];
document.getElementById("demo").innerHTML = companies;

function myFunction() {
    companies.splice(2, 1, "Infosys", "TCL");
    document.getElementById("demo").innerHTML = companies;
}
</script>
</body>

In this example, we are removing one element at second index and adding two new an element at companies array index 2. The resulting array element of companies is Apple,Google,Infosys,TCL,IBM, and where second element Facebook is remove from an array list.

Example 2:  Here we are removing the element from the existing array and add the removed element to a new array called sliced.

<body>
<p>Click the button to add and remove elements.</p>
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
New sliced array
<p id="sliced"></p>

<script>
function myFunction() {
	var oldArray = ['zero', 'one', 'two', 'three'];
	var sliced = oldArray.splice(2, 3);
	document.getElementById("demo").innerHTML = oldArray;
	document.getElementById("sliced").innerHTML = sliced;
} 
</script>
</body>

Output of the above code, oldArray :[ “zero”,”one”] and new sliced  : “[two”,”three”]

 

To remove an item from the list

To bill Status – Javascript Project 1

In this example, we are learning Javascript local storage to store the list of our bill status. The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed and will be available the next day, week, or year.

The localStorage store data in name/value pair and example below we have an example to set and retrieving data from local storage.

What are we learning?

  1. HTML local storage
  2. DOM manipulation and event listener of Javascript
<div id="result"></div>

<script>
// Check browser support

if (typeof(Storage) !== "undefined") {
    // Store
    localStorage.setItem("name", "Gangchenpa");
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("name");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>

 

The screenshot of our Javascript Bill status example 

In this example, we have an input box to add new bill with bill status not paid, as in the checkbox with ticked indicate bill paid. We can delete the billing record from the local storage by clicking on icon recycle bin.

Step 1: Add the following code in index.html to display the input box and list of all bill record from local storage when the constructor of a class is called.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Bill Status</title>
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>

  <div class="container">

    <div class="content-area row">
      <div class="col-md-2 col-xs-2 col-lg-2 col-sm-2"></div>

      <div class="col-md-8 col-xs-8 col-lg-8 col-sm-8">
        <h2>Bill payment status </h2>

        <div class="row input-area">
          <div class="col-md-1"></div>
          <div class="form-group col-md-9">
            <input type="text" placeholder="New Bill" class="form-control" id="addBill">
          </div>
          <div class="form-group col-md-1">
            <button class="btn btn-primary" onclick="toDo.addBillClick()">Add</button>
          </div>
          <div class="col-md-1"></div>
        </div>

        <ul class="list-group" id="billList">

        </ul>
      </div>

      <div class="col-md-2 col-xs-2 col-lg-2 col-sm-2"></div>
    </div>

  </div><!-- /.container -->

  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <script src="scripts.js"></script>
</body>
</html>

In the highlight ul tag, we are loading all the bill item from local storage when a browser loads the page. We have a function in index.html.

toDo.addBillClick(): to add new Bill record to the local storage BILLS object

Step 2: We have to add Javascript code to add, delete bill item to local storage. 

class BillClass {
    constructor() {
      this.bills = JSON.parse(localStorage.getItem('BILLS'));
      if(!this.bills) {
        this.bills = [
          {bill: 'Room rent', isPaid: false},
          {bill: 'Electricity bill', isPaid: true},
          {bill: 'Internet bill', isPaid: false},
        ];
      }

      this.loadBills();
      this.addEventListeners();
    }

    addEventListeners() {
      // Add bill
	  
      document.getElementById('addBill').addEventListener("keypress", event => {
        if(event.keyCode === 13) {
          this.addBill(event.target.value);
          event.target.value = "";
        }
      });
    }

    addBillClick() {
      let target = document.getElementById('addBill');
      this.addBill(target.value);
      target.value = ""
    }

    addBill(bill) {
      let newBill = {
        bill,
        isPaid: false,
      };
      let parentDiv = document.getElementById('addBill').parentElement;
      if(bill === '') {
        parentDiv.classList.add('has-error');
      } else {
        parentDiv.classList.remove('has-error');
        this.bills.push(newBill);
        this.loadBills();
      }
    }

    toggleBillstatus(index) {
      this.bills[index].isPaid = !this.bills[index].isPaid;
      this.loadBills();
    }

    deleteBill(event, billIndex) {
      event.preventDefault();
      this.bills.splice(billIndex, 1);
      this.loadBills();
    }

    generateBillHtml(bill, index) {
      return `
        <li class="list-group-item checkbox">
          <div class="row">
            <div class="col-md-1 col-xs-1 col-lg-1 col-sm-1 checkbox">
              <label>
                <input id="togglebillstatus" type="checkbox" onchange="toDo.togglebillstatus(${index})" value="" 
                  class="" ${bill.isPaid?'checked':''}>
              </label>
            </div>
            <div class="col-md-10 col-xs-10 col-lg-10 col-sm-10 bill-text ${bill.isPaid?'Paid':''}">
              ${bill.bill}
            </div>
            <div class="col-md-1 col-xs-1 col-lg-1 col-sm-1 delete-icon-area">
              <a class="" href="/" onClick="toDo.deleteBill(event, ${index})">
                <i id="deleteBill" data-id="${index}" class="delete-icon glyphicon glyphicon-trash"></i>
              </a>
            </div>
          </div>
        </li>
      `;
    }

    loadBills() {
      localStorage.setItem('BILLS', JSON.stringify(this.bills));
      let billsHtml = this.bills.reduce((html, bill, index) => html += this.generateBillHtml(bill, index), '');
      document.getElementById('billList').innerHTML = billsHtml;
    }
}

let toBill;

window.addEventListener("load", () => {
  toBill = new BillClass();
});
What we are learning
  1.  We are using event listener keypress on input text box and the keyCode 13 indicate enter key.
  2. Use of reduce() method on bills array object: bills.reduce((html, bill, index) – to load all the bill record from local storage to accumulator HTML variable and bill is a current element of bills array record.
  3. Create toBill object when window event listener load the page
    window.addEventListener("load", () => {
        toBill = new BillClass();
    });

 

JavaScript Tutorial

  1. Javascript variable scope
  2. Arrow Function
  3. Function programming in JavaScript to perform an operation (map, filter, reduce )on collection or an array.
  4. Javascript an Array function – (splice())

Javascript Project:

  1. To bill status – learning (add/delete of bill item local storage, window.addEventListener [keypress code 13])

Arrow function:

ES6 has introduced arrow functions. First, they have a concise syntax. Secondly, they have implicit returns, which allows us to write these nifty one-liners.

Advantage:

  1. An arrow function simply inherits this object of its parent instead of binding its own, so we don’t need to specify binding of this keyword.
  2. Arrow function allows implicit returns, no need to write return keyword, as result, we have shorter syntax and no binding of this
    Traditional method have return values as
    
    let sum = function(x, y) {
        return x + y;
    }
    
    Arrow function without return keyword
    let sum = (x, y) => x+y;

 

Javascript Variable Scope

When we are learning the programming language, each language has its own variable scope.  In the Javascript, both function and object are also variables.  We can declare a variable in many locations inside, outside the function and object. Based on the location of variable it has the scope.

By the scope, we mean the lifetime of a variable i.e where the variable is visible and available for us to use in our code. In JavaScript, we have not many but just a couple of different types of scopes. In the Javascript we have

  1. Local Variable
  2. Global Variable

ES6 has introduce two new keywords for declaring variables,

  1. let
  2. const

The scope of variables declared using var is within the function it is defined and global if it is not defined inside any function, while the scope of let is restricted to within the enclosing block it was declared in and global if it is not defined inside any enclosing block.

Const keyword :
The working of const is the same as that of let, except that variables declared using const cannot be changed (reassigned). Hence, const is used for constants. However, an entire constant cannot be reassigned but their properties can be changed. For example:

const a = 5;
// this will not work
a = 7; 
const b = {
	a: 1,
	b: 2
};
 // this will not work
 
b = { a: 2, b: 2 };

// this will work since only a property of b is changed
b.a = 2; 

Local variable: When a variable is declared inside the function it has local scope. The local variable only visible and accessed within the function where it was declared. The local variable dies when function finished its task.

Global Variable: When the variable is declared outside of the function it becomes global variable and can be accessed from anywhere in the code.

The Javascript does not implement block scoping. We can achieve block with help of let keyword. In the example here we can access variable i and inFor outside the for loop block.

function scopeTest() {
   for (var i = 0; i <= 5; i++){
     inFor = i; 
   }
  console.log("Value of inFor" +inFor);  
  console.log("Value of i" +i);
}

The output of above code inFor as 5 and i as 6.  In the new version of Javascript allow us to use new keyword called let to achieve block level in the loop. Variables declared with let inside a block scope are only accessible inside that scope. If we use let to declare the i variable in a for loop, that variable will only be available inside the for a loop.

function scopeTest() {
   for (let i = 0; i <= 5; i++){
        inFor = i; 
   }
   console.log("Value of inFor" +inFor);  
   console.log("Value of i" +i);
}

For above code output value of inFor is 5 and we can’t access the i value outside so it will generate output message as Uncaught ReferenceError: i is not defined.

Static Variable scoping:
Here we are learning static variable scope in Javascript with D3 library.  Add the following code in our filename.js file.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
    <title>Functional Javascript</title>
    <link rel="stylesheet" type="text/css" href="css/style.css"/>
    <script type="text/javascript" src="node_modules/d3/build/d3.js"></script>
</head>

<body>

<script type="text/javascript">
    function simpleFunObject(spec) {
        var instance = {}; 
        var headline, description; 

        instance.render = function () {
            var div = d3.select('body').append("div");

            div.append("h3").text(headline); 

//Adding box class and color to parent div 
            div.attr("class", "box") 
               .attr("style", "color:" + spec.color) 
               .append("p")
                   .text(description); 

            return instance; 
        };

        instance.headline = function (h) {
            if (!arguments.length) return headline; 
            headline = h;
            return instance; 
        };

        instance.description = function (d) {
            if (!arguments.length) return description;
            description = d;
            return instance;
        };

        return instance; 
    }

    var testScope = simpleFunObject({color: "#718024"})
            .headline("Javascirpt static variable scope")
            .description("This is a example of simple functional object in javascript.");
    testScope.render();
</script>

</body>
</html>

In above code, all three variable instance, headline, description are private variable belongs to the simplFunObject function object.  The function simpleFunObject is a functional object and we can assign it variable and called render() method. Render refers to show output in the browser and utilize the document object to manipulate DOM elements.

In the Javascript Scoping is static, it is determined by the nesting of syntactic constructs. The variable scoping is actually determined by a simple static scoping rule. This rule can follow as, whenever the runtime searches for a variable reference, the search will be performed first locally. When a variable declaration is not found in second highlight headline in code, search will perform first in local then it search continue toward the parent object, if still not found, then this process will continue recursively to next parent, so on and so forth, till it reaches a global variable definition, if it is still not found then a reference error will be generated for this variable.

Javascript Timer count down

Javascript code to countdown timer from 3 seconds.

<!DOCTYPE html>
<html>
<style>
#adsTimer{
	padding:4px;
	font-size: 2em;
    display: inline-block;
  	width: 95px;
    color: #fff;
    background-color: #ff0000;
    border: 2px solid #ff0000;
    border-radius: 2px;
}
</style>
<body>

<span id="adsTimer"></span>

<script>
var timeLeft = 10;
var elem = document.getElementById('adsTimer');
var adsTimer = setInterval(countdown, 1000);

 

function countdown() {
    if (timeLeft == 0) {
        clearTimeout(adsTimer);
        endOfTimer();
        
    } else {
        elem.innerHTML = timeLeft + ' secs';
        timeLeft--;
    }
}

function endOfTimer() {
    elem.style.display = "none";
}
</script>
</body>
</html> 

Js code

1. We are creating js multiple choice question

Screenshot of multiple choice question answer 

We creating a separate article element for each question and its answers. Here all the answer are creating through checkbox element.
Each checkbox value is the question number start from 0 and an answer value.
Eg <input type=”checkbox” id=”options00″ value=”0:Modi” name=”option0″>Modi

We have two for loop, first is iterating through each question and second j for loop is for iterating through each answer options of that particular question.

<html>
<head>
	<script>
	function init(){
		var questions = '[{ "question":"Select names of India prime minister?", "options":["Modi", "Rahul Gandhi", "Nehru"], "answer":["Modi", "Nehru"]}, 
{"question":"What is second question?", "options":["Aloo", "Gobi"], "answer":["Gobi"]}]';

		var dataModel = JSON.parse(questions);
		for(i =0; i<dataModel.length;i++) {

			var article = document.createElement('article');
			article.innerHTML = "<p>" + dataModel[i].question + "</p>";

			for(j=0;j<dataModel[i].options.length;j++){
				var checkbox = document.createElement('input');
				checkbox.setAttribute("type","checkbox");
				checkbox.setAttribute("id","options" + i + "" + j);
				checkbox.setAttribute("value", i + ":" + dataModel[i].options[j]);
				checkbox.setAttribute("name","option" + i);

				var label = document.createElement("label");
				label.setAttribute("for","options" + i + "" + j);
				label.innerHTML = dataModel[i].options[j];

				var breakTag = document.createElement("br");

				article.append(checkbox);
				article.append(label);
				article.append(breakTag);
			}
			document.getElementById("questions").append(article);
	}
// end of i for loop

			var button = document.createElement('button');
			button.innerHTML = "Submit";

			button.onclick = function(){
				var checkboxElements = document.querySelectorAll('[id^=options]');
				var score = 0;

				for(let i=0; i < checkboxElements.length; i++){
					if(checkboxElements[i].checked){
						var options = checkboxElements[i].value.split(":");
            var correctAnswer = dataModel[options[0]].answer.filter( (data) =>
              data === options[1]
            );

						if(correctAnswer.length >= 1)
							score++;
					}
				}
				console.log("Total answer score : ",score);

				showResults(score);
			}

			var breakTag = document.createElement("br");
			document.getElementById("questions").append(breakTag);
			document.getElementById("questions").append(button);
	}

	function showResults(score){
		var scoreSection = document.getElementById("score");

    removeNodes(scoreSection);
    var article = document.createElement("article");
		article.innerHTML = "<p> You'r score is <b> " + score + "</b></p>";
		scoreSection.append(article);
	}

  function removeNodes(node){
    while (node.hasChildNodes())
      node.removeChild(node.lastChild);
  }

	window.onload = init;
	</script>
</head>
<body>
		<header>
			<center>Quiz Applcation</center>
		</header>
		<hr/>
		<section id="questions">
		</section>
		<section id="score">
		</section>
</body>
</html>

Once the user clicks on the submit button we will be iterating through each checkbox element list and check if checkbox click is the correct answer. This can be achieved when checkbox element is checked and then we have to use javascript split function to separate checkbox value contain question number and answer.
As value=”0:Modi”
Where 0 is the first question and Modi is a value of checkbox answer of that question.

var correctAnswer = dataModel[options[0]].answer.filter( (data) =>
data === options[1]
);

In above code, we are iterating through each answer to that particular question and check if the answer is correct. For the first question, we have to iterate 3 times in answer and 2 iterations for the second answer. As the filter will create a new array containing correct checkbox answer.

showResults to create element containing the score result and we have used remove function to delete the existing score result node. So that duplication of score element will remove when ever new score is created.

 

We are using function

Javascript to sort the beginning match string in input reserved word list

  1. Add wordlist in searchWord.js
    window.getSearchWords = function() {
        return [
    	'angular',
    	'angularjs',
      	'ionic',
    	'javascript',
    	'node',
    	'php',
    	'pull',
    	'push',
    	'note'
        ];
    };
  2. Add following code in search, we can split the data into two arrays, one that starts with input and one. Sort each separately, then combine the two results:
     function sortInputMatch(input, data) {
            var first = [];
            var others = [];
            for (var i = 0; i < data.length; i++) {
                if (data[i].indexOf(input) == 0) {
                    first.push(data[i]);
                } else {
                    others.push(data[i]);
                }
            }
            first.sort();
            others.sort();
            return (first.concat(others));
        }
    
        var results = sortInputMatch(query, matches);