Object Oriented Programming Articles - Page 235 of 701

How to create a function which returns only even numbers in JavaScript array?

AmitDiwan
Updated on 18-Aug-2020 07:22:21

1K+ Views

Here, we need to write a function that takes one argument, which is an array of numbers, and returns an array that contains only the numbers from the input array that are even.So, let's name the function as returnEvenArray, the code for the function will be −Exampleconst arr = [3,5,6,7,8,4,2,1,66,77]; const returnEvenArray = (arr) => {    return arr.filter(el => {       return el % 2 === 0;    }) }; console.log(returnEvenArray(arr));We just returned a filtered array that only contains elements that are multiples of 2.OutputOutput in the console will be −[ 6, 8, 4, 2, 66 ]Above, we returned only even numbers as output.

Filtering of JavaScript object

AmitDiwan
Updated on 18-Aug-2020 07:21:11

265 Views

Here we need to create a function that takes in an object and a search string and filters the object keys that start with the search string and returns the objectHere is the code for doing so −Exampleconst obj = {    "PHY": "Physics",    "MAT": "Mathematics",    "BIO": "Biology",    "COM": "Computer Science",    "SST": "Social Studies",    "SAN": "Sanskrit",    "ENG": "English",    "HIN": "Hindi",    "ESP": "Spanish",    "BST": "Business Studies",    "ECO": "Economics",    "CHE": "Chemistry",    "HIS": "History" } const str = 'en'; const returnFilteredObject = (obj, str) => {    const filteredObj = {}; ... Read More

Display array items on a div element on click of button using vanilla JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:19:57

4K+ Views

To embed the elements of an array inside a div, we just need to iterate over the array and keep appending the element to the divThis can be done like this −Exampleconst myArray = ["stone", "paper", "scissors"]; const embedElements = () => {    myArray.forEach(element => {       document.getElementById('result').innerHTML +=       `${element}`;       // here result is the id of the div present in the DOM    }); };This code makes the assumption that the div in which we want to display the elements of array has an id ‘result’.The complete code for this ... Read More

Combine objects and delete a property with JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:17:45

248 Views

We have the following array of objects that contains two objects and we are required to combine both objects into one and get rid of the chk property altogether −const err = [    {       "chk" : true,       "name": "test"    },    {       "chk" :true,       "post": "test"    } ];Step 1 − Combining objects to form a single objectconst errObj = Object.assign(...err);Step 2 − Removing the chk propertydelete errObj['chk']; console.log(errObj);Let us now see the entire code with output −Exampleconst err = [    {       ... Read More

Mobile

Clearing localStorage in JavaScript?

AmitDiwan
Updated on 18-Aug-2020 07:16:30

552 Views

There exists two ways actually to clear the localStorage via JavaScript.Way1 − Using the clear() methodlocalStorage.clear();Way2 − Iterating over localStorage and deleting all keyfor(key in localStorage){ delete localStorage[key]; }Both ways will work.Example if (typeof(Storage) !== "undefined") {    localStorage.setItem("product", "Tutorix");    // cleared before displaying    localStorage.clear();    document.getElementById("storage").innerHTML = localStorage.getItem("product"); } else {    document.getElementById("storage").innerHTML = "Sorry, no Web Storage    compatibility..."; }

Find number of spaces in a string using JavaScript

Nikitasha Shrivastava
Updated on 18-May-2023 12:20:46

3K+ Views

In this problem statement, our task is to find the number of spaces in a string with the help of Javascript functionalities. This task can be done with the help of the split method of Javascript. This method can be useful to split the string into an array of substrings as per the spaces. Logic for the given problem The problem stated that we have to find the number of spaces in a given string and we will use the split method. So at the very first step we will split the string and create an array of substrings as ... Read More

Why does Array.map(Number) convert empty spaces to zeros? JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:14:05

445 Views

Let’s say we are given the following code and output and we need to figure out why JavaScript converts empty strings(“ “) to 0 −const digify = (str) => {    const parsedStr = [...str].map(Number)    return parsedStr; } console.log(digify("778 858 7577"))Output[ 7, 7, 8, 0, 8, 5, 8, 0, 7, 5, 7, 7 ]This behaviour can be very disturbing especially when we have some 0 in the string as wellThis actually happens because inside of the map() function when we are converting each character to its numerical equivalent using Number, what it does is it actually uses Abstract Equality ... Read More

How to set attribute in loop from array JavaScript?

AmitDiwan
Updated on 18-Aug-2020 07:12:47

1K+ Views

Let’s say we are required to write a function that takes in an array and changes the id attribute of first n divs present in a particular DOM according to corresponding values of this array, where n is the length of the array.We will first select all divs present in our DOM, iterate over the array we accepted as one and only argument and assign the corresponding id to each div −The code for doing the same is −const array = ['navbar', 'sidebar', 'section1', 'section2', 'footer']; const changeDivId = (arr) => {    const divsArray = document.querySelectorAll('div');    arr.forEach((element, index) ... Read More

Get filename from string path in JavaScript?

AmitDiwan
Updated on 18-Aug-2020 07:12:00

2K+ Views

We need to write a function that takes in a string file path and returns the filename. Filename usually lives right at the very end of any path, although we can solve this problem using regex but there exists a simpler one-line solution to it using the string split() method of JavaScript and we will use the same here.Let’s say our file path is −"/app/base/controllers/filename.jsFollowing is the code to get file name from string path −Exampleconst filePath = "/app/base/controllers/filename.js"; const extractFilename = (path) => {    const pathArray = path.split("/");    const lastIndex = pathArray.length - 1;    return pathArray[lastIndex]; ... Read More

How to convert array to object in JavaScript

AmitDiwan
Updated on 18-Aug-2020 07:11:12

417 Views

Let’s say we need to convert the following array of array into array of objects with keys as English alphabetconst data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];This can be done by mapping over the actual arrays and reducing the subarrays into objects like the below example −Exampleconst data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]; const dataArr = data.map(arr => { return arr.reduce((acc, cur, index) => ({    ...acc,       [String.fromCharCode(97 + index)]: cur    }), Object.create({})) }); console.log(dataArr);OutputThe console output for this code will be −[    { a: 1, b: 2, c: 3, d: 4 },    { a: 5, b: 6, c: 7, d: 8 },    { a: 9, b: 10, c: 11, d: 12 } ]

Advertisements