NodeJS – Step by Step Procedure to Setup and Create a NodeJS application and use TypeScript as a Programming Language

Sathish Nadarajan
 
Solution Architect
October 1, 2021
 
Rate this article
 
Views
1015

All of us are familiar about the popularity and the power of Node JS. By default the NodeJS application will have the start page as a JS file and predominantly it is meant for the JavaScript. But, when I wanted to create a Node WebSite, which is going to interact with SharePoint Online using PNPJS, I was in a situation that, TypeScript is more friendlier than JS for any PNP and SharePoint Online coding.

Hence, wanted to explore, how to create or use Typescript within the Node JS application and make the DEV environment a bit faster and cleaner.

In this article, let us see the steps to create a NodeJS application and use typescript as a Programming Language on it.

1. Install Node LTS from the below path.

https://nodejs.org/en/download/

 

 

 

2. Ensure that the Node is installed properly by typing “node -v”. This will give the version of the node installed.

3. Create a folder with the app name – C:\NodeApps\DemoNodeJSWithTypeScript
4. Open the command prompt.

5. Create a solution using “npm init”.

6. The command will create the package.json file.

 

Package.json

{
"name": "demonodejswithtypescript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC"
}

7. Install TypeScript using the command npm install -g typescript

8. Ensure the version of typescript by tsc –version

9. We need to create the config file for the TypeScript. Tscofig.json.
a. We can create this by running the command “tsc –init”.

 

10. Now, the tsconfig.json has been created. Have a look on the site, for more information about the tsconfig.
11. Update the tsconfig as below.

{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
"target": "es6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"exclude": [
"./node_modules"
]
}

12. Create the folders SRC and DIST as updated above on the tsconfig.json file. The folder structure will looks as below.

 

13. Create a file called index.ts inside the src folder.
14. Write some TS code here.

function sum (num1:number, num2:number){
return num1 + num2;
}
console.log(sum(8,4))

15. Now, install the typescript compiler npm install -D typescript

16. Now run tsc ;- this will create the corresponding index.js on the outdir dist folder.

17. Now, the solution and the index.js will be shown as below.

 

18. Now execute “node dist/index.js” to run the application.

 

19. Install ts-node by “npm install -D ts-node
a. Ts-node allows us to point to a Typescript file. It will run .ts, compile it and run it with Node.js for us.
20. Update the config file as below.

{
"name": "demonodejswithtypescript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "ts-node ./src/index.ts"
},
"author": "",
"license": "ISC",
"devDependencies": {
"ts-node": "^10.2.1",
"typescript": "^4.4.3"
}
}

21. Now we can execute by using “npm start” itself. This will automatically trigger the index.ts file.
22. Then install the below packages for various purposes.

Npm install express
Npm install -D @types/node
Npm install -D @types/express

 

23. Update the index.ts as below.

import express, { Application, ErrorRequestHandler, Request, response, Response } from 'express';

const app: Application = express();
const PORT = process.env.PORT || 2000;

app.get("/", async (req: Request, res: Response): Promise => {

res.send("Hello Typescript with Node.js!")

});

app.use(function (err: any, req: Request, res: Response, next: ErrorCallback) {
res.status(err.status || 500);
res.send(err);
});

app.listen(PORT, (): void => {
console.log(`Server Running here https://localhost:${PORT}`);
});

24. Now run “npm start

 

25. Browse the page http://localhost:2000

 

26. The next step is to continuously monitor the TS files changes, so that the npm server should automatically refresh. For that, I prefer to go with Nodemon.

27. Npm install -D nodemon

28. Update the package.json with the script parameter dev. The final package.json will looks like below.

{
"name": "demonodejswithtypescript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "ts-node ./src/index.ts",
"dev": "nodemon ./src/index.ts"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/express": "^4.17.13",
"@types/node": "^16.10.2",
"ts-node": "^10.2.1",
"typescript": "^4.4.3"
},
"dependencies": {
"express": "^4.17.1"
}
}

29. Now we can use the command “npm run dev

Though it’s a bit lengthy, this will be useful for someone who wants to develop a Node application with TypeScript. Especially the stand alone application for the SharePoint Online. Yes, this is a start and the objective is to use this application with PNPJS to interact with SharePoint Online sites in the upcoming articles. Stay Tuned!!!

Download the Source HERE

Happy Coding
Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

ElectronJS – Step by Step Procedure to Setup and Create a Hello World App using Electron JS

Sathish Nadarajan
 
Solution Architect
September 14, 2021
 
Rate this article
 
Views
1485

In this article, let us see the step by step procedure to create my first hello world app using Electron JS

1. Install Node LTS from the below path.
https://nodejs.org/en/download/

 

 

2. Create a folder with the app name – C:\ElectronApps\HelloWorldElectron
3. Open the command prompt.

 

4. Create a solution using “npm init”.

 

5. The command will create the package.json file.

 

6. Install Electron JS using the command

npm install –save-dev electron

 

7. Try starting the application.
Npm start

 

We may get the above exception. This means, we haven’t created the main.js file. Let us create the main.js.

And the Preload.js and the index.js

Then again “npm start”. The output will be as shown below.

8. The finished code of different files are as below.

Package.json

{
"name": "helloworldelectron",
"version": "1.0.0",
"description": "MyDescription for helloworldelectron",
"main": "main.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "electron ."
},
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "^14.0.0"
}
}

Main.js

// main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('path')

function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})

// and load the index.html of the app.
mainWindow.loadFile('index.html')

// Open the DevTools.
// mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()

app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

Preload.js

// preload.js

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}

for (const dependency of ['chrome', 'node', 'electron']) {
replaceText(`${dependency}-version`, process.versions[dependency])
}
})

Index.html

<!--index.html-->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.

    <!-- You can also require other files to run in this process -->
    <script src="./renderer.js"></script>
  </body>
</html>

 

Happy Coding
Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Refreshing JavaScript – Calling an Async method within Map method in Typescript – SPFx

Sathish Nadarajan
 
Solution Architect
August 27, 2021
 
Rate this article
 
Views
1118

Recently faced an issue. I need to iterate a list of items and need to call an Async method. But the map needs to wait until the last async method is been returned. Usually what happens is, since the method is async, after the first value, it goes beyond the map method and returns. For that, we must write the method with async and Promise All. The pseudo method is as below.

public getTasks = async (Id: number): Promise<any> => {
    try {
      let tasksListItems = await sp.web.lists.getByTitle('Tasks').items.expand('AssignedTo').select('*', 'AssignedTo/Title', 'AssignedTo/EMail', 'AssignedTo/Name').filter(`ProjectID eq ${Id} `).get();

      let taskIds = [];
      taskIds = await Promise.all(tasksListItems.map(async item => {
        return {
          key: item.Id,
          text: item.AssignedTo1.Title,
          taskTitle: item.Title,
          isMember: await graphDataProvider.isMemberOfOffice365Group(item.AssignedTo.Name.split('|')[2], await this.getCurrentUserPrinciple())
        }
      }));
      return taskIds.filter(task => task.isMember);
    }
   catch (error) {
      return null;
    }
  }

Points to be considered.
1. The method should be declared as async method.
2. The map should be surrounded with await Promise.all()
3. Within the map method, we can very well call the async method using the await keyword.

Happy Coding
Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Refreshing JavaScript – Push Un-Shift methods in Array.

Sathish Nadarajan
 
Solution Architect
August 16, 2021
 
Rate this article
 
Views
499

Arrays are very common datatype which we will be using in our Day-to-day life. In which inserting the records and retrieving based on
the index is very common scenario.

Push: – To Insert an item at the bottom of the array, we will use the Push method.

Un-Shift: – To Insert an item at the top of an array, we can use unshift method.

The example is as follows.

myParentArray.map(parentArrayItem => {
          if (parentArrayItem.Action != null) {
            childArray.push({
              Id: parentArrayItem.Id,
              Title: parentArrayItem.Title,

            })

          }
          else {
            childArray.unshift({
              Id: parentArrayItem.Id,
              Title: parentArrayItem.Title,
             })
          }
        })

In the above example, if the parentArrayItem.Action has value, then it will be pushed at the bottom of the ChildArray. If there is no Action, then it will be placed on the top of the ChildArray.

Happy Coding
Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

SPFX – Array Manipulation Using TypeScript – Explained with SetTheory Concepts

Sathish Nadarajan
 
Solution Architect
August 3, 2021
 
Rate this article
 
Views
1598

Almost in every application or webpart, any developer would be dealing with the Array and any type of collection.  There are few scenarios which I faced with respect to the Difference, Union etc., Just wanted to share with the audience.

For the below article, let us use the basic Arrays.  I have two Array of file names.

One with the total files which I have in a document library.

allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]

The Second one, only the required files.

filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]

 

Difference

Basically, I need to delete the files “File1, File3 and File4”.  To identify that, doing a for loop and all, I don’t want to do that.  The simplest way is as below.

 

allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
let filesToBeDeleted = allFilesInsideFolder.filter(x => !filesToCopy.includes(x));
filesToBeDeleted = [‘File1.txt’,‘File3.txt’, ‘File4.txt’]

 

Intersection

May be, in some scenario if I want only the files which are available on both the array, then

 

allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
let intersectionFiles = allFilesInsideFolder.filter(x => filesToCopy.includes(x));
intersectionFiles = [ ‘File2.txt’, ‘File5.txt’]

 

Symmetric Difference

In case, if I want only the unique files, i.e., any file which is present either in allFilesInsideFolder or filesToCopy array, then

 

allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
let symmetricdifference = allFilesInsideFolder
.filter(x => ! filesToCopy.includes(x))
.concat(filesToCopy.filter(x => ! allFilesInsideFolder.includes(x)));
symmetricdifference = [ ‘File1.txt’, ‘File3.txt’,‘File4.txt’,‘File6.txt’]

 

Union

In case, if I want both the array elements, then

 

allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
let union = [...allFilesInsideFolder, ... filesToCopy];
union = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’, ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]

 

This will have duplicates.  But the distinct union will not have duplicates.

 

Distinct Union

If I want the distinct elements in both the arrays, then

 

allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
let distinctunion = [...new Set([...allFilesInsideFolder, ... filesToCopy)];
distinctunion = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’, ‘Files6.txt’]

 

Happy Coding

Sathish Nadarajan

 

 

 

 

 

 

 

 

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Step by Step Procedure to Create a PowerPoint Add-In

Sathish Nadarajan
 
Solution Architect
January 21, 2021
 
Rate this article
 
Views
3672

In an earlier article, we saw how to create a simple Outlook AddIn. AS part of that, in this article, let us how to create a PowerPoint AddIn.

1. Create a New Project in Visual Studio.

2. Choose the Add-in Type. In our case, we are going to add new functionality to Power Point.

3. The Solution will get created as below.

It comprises of two projects. One is the Web Application which we need to deploy in any of the domain or in Azure Web Service.
The First One contains only the XML file which we need to distribute to the end Users. There are few mechanisms, by which we can deliver this to the end users.
4. Now, let us come back and have a look on the components of the solution. The three important files in which we are making changes are Home.html, Home.css, Home.js.
5. My requirement was to display a set of Images on the task pane. And when the User Clicks, the Image should be inserted into the slide.

 

6. Let us how to update the HTML file to list all our Images on the Task Pane.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />

    <script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="Scripts/FabricUI/MessageBanner.js" type="text/javascript"></script>
    <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>

    <!-- To enable offline debugging using a local reference to Office.js, use:                        -->
    <!-- <script src="Scripts/Office/MicrosoftAjax.js" type="text/javascript"></script>  -->
    <!-- <script src="Scripts/Office/1/office.js" type="text/javascript"></script>  -->

    <link href="Home.css" rel="stylesheet" type="text/css" />
    <script src="Home.js" type="text/javascript"></script>

    <!-- For the Office UI Fabric, go to https://aka.ms/office-ui-fabric to learn more. -->
    <link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.1.0/fabric.min.css">
    <link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.1.0/fabric.components.min.css">

    <!-- To enable the offline use of Office UI Fabric, use: -->
    <!-- link rel="stylesheet" href="Content/fabric.min.css" -->
    <!-- link rel="stylesheet" href="Content/fabric.components.min.css" -->
</head>
 

<body class="ms-font-m ms-welcome">
    <div id="content-header">
        <div class="cls-title"><span>PP Image Library</span></div>
    </div>
    <div id="content-main">
        <div class="padding">
            <p>Double click on an item and insert it to the slides.</p>
            <div class="container" style="padding: 8px;">

                <img id="1" crossOrigin="anonymous" class="myimages" src="https://source.unsplash.com/600x600/?sig=1" alt="1.jpg"/>
                <img id="2" crossOrigin="anonymous" class="myimages" src="https://source.unsplash.com/600x800/?sig=12" alt="1.jpg"/>
                <img id="3" crossOrigin="anonymous" class="myimages" src="https://source.unsplash.com/800x600/?sig=71" alt="1.jpg"/>
                <img id="4" crossOrigin="anonymous" class="myimages" src="https://source.unsplash.com/600x600/?sig=40" alt="1.jpg"/>
                <img id="5" crossOrigin="anonymous" class="myimages" src="https://source.unsplash.com/600x600/?sig=32" alt="1.jpg"/>

            </div>




        </div>
    </div>
</body>

</html>

7. The corresponding JS file would be as below.

'use strict';

(function () {

    Office.onReady(function () {
        // Office is ready
        $(document).ready(function () {
            // The document is ready
             
            $('.myimages').click(insertImage);
        });
    });

     
    var imagebase64 = "";  

    function insertImage(id) {

        console.log(id);

        var src = $(id)[0].currentTarget.href;

        var img = document.getElementById($(id)[0].currentTarget.id);

        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;

        //img.crossOrigin = 'anonymous';
        //img.setAttribute('crossOrigin', 'anonymous');
        ctx.drawImage(img, 0, 0);

        var temp = canvas.toDataURL().split(',')[1];


         
        Office.context.document.setSelectedDataAsync(temp, {
            coercionType: Office.CoercionType.Image,
            imageLeft: 50,
            imageTop: 50
            //imageWidth: 400
            //imageHeight: canvas.height
        },
            function (asyncResult) {
                if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                    console.log(asyncResult.error.message);
                }
            });
    }

    function insertText() {
        Office.context.document.setSelectedDataAsync("Hello World!",
            function (asyncResult) {
                if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                    console.log(asyncResult.error.message);
                }
            });
    }
})();

8. No need to explain about the CSS. It depends on the end users.
9. Now, hit F5 from the Visual Studio.
10. The PowerPoint Opens with our Add-In Visible.

11. On Click of that, the task pane (home.html) will get opened and rendered with the Images.

12. On Click of any image, the corresponding image will be inserted into the Slide.

13. The InsertImage method is responsible for inserting the image into the slide.

function insertImage(id) {

        console.log(id);

        var src = $(id)[0].currentTarget.href;

        var img = document.getElementById($(id)[0].currentTarget.id);

        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;

        //img.crossOrigin = 'anonymous';
        //img.setAttribute('crossOrigin', 'anonymous');
        ctx.drawImage(img, 0, 0);

        var temp = canvas.toDataURL().split(',')[1];


        //var reader = new FileReader();
        //reader.onloadend = function () {
        //    imagebase64 = reader.result;
        //};
        //reader.readAsDataURL(img.href);  

        //Office.context.document.setSelectedDataAsync(getImageAsBase64String(src), {
        Office.context.document.setSelectedDataAsync(temp, {
            coercionType: Office.CoercionType.Image,
            imageLeft: 50,
            imageTop: 50
            //imageWidth: 400
            //imageHeight: canvas.height
        },
            function (asyncResult) {
                if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                    console.log(asyncResult.error.message);
                }
            });
    }

In the next article, let us see how to Publish and Deploy this Add-In.

Happy Coding,
Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Add SharePoint List Items using Batching & SP Editor Chrome Extension

Ahamed Fazil Buhari
 
Senior Developer
April 19, 2020
 
Rate this article
 
Views
1827

When we want to fix something quickly then using SP Editor chrome extension gives an oppotunity to run JS script from your browser in Developer Tool.

speditor

 

paste the following script to add items to SharePoint list using batching and hit CTRL+D to run the script

import { sp } from "@pnp/sp/presets/all";
(async () => {
  console.clear();
  let list = sp.web.lists.getByTitle("Large");
  const entityTypeFullName = await list.getListItemEntityTypeFullName();
  let batch = sp.web.createBatch();

  const totalItems = 6000;
  for (var i = 1; i < totalItems; i++) {
    console.log(`Adding Batching for Item ${i}`);
    list.items.inBatch(batch).add({ Title: `Item ${i}` }, entityTypeFullName);

    if(i % 100 === 0) {
        console.log(`Executing Batch for 100 Items`);
        await batch.execute();
        batch = sp.web.createBatch();
    }
  }
})().catch(console.log)

logg

In the console window you can see the item being added using batching.

Happy Coding
Fazil

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Refreshing JavaScript – Reduce Method – Detailed Explanation

Sathish Nadarajan
 
Solution Architect
May 2, 2019
 
Rate this article
 
Views
503

Definition:

.reduce() – A method which iterates through an array or collection and returns a reduced object.  The speciality is, the object which returns will be given as input for the next iteration.  To be more detailed, the reduce method can have a callback function, for which, the previous object in the array will become the input.  If it is not clear, let us have a look on the Example, so that we can understand much.

Example:

I have an Array of Employees.

 employees = [
             {
                 id:10,
                 Age:30
             },
             {
                 id:11,
                 Age:27
             },
             {
                 id:13,
                 Age:40
             }
         ];
 

In this array, I want to identify, which employee is the aged one.  For that, the output, I am expecting is a single object from the array.  I don’t want to do a for loop to identify this.  Instead, we can use the Reduce method.

 var agedEmployee = employees.reduce(function(oldest,employee){
             return (oldest.Age || 0) > employee.Age ? oldest : employee
         });
 
         console.log(agedEmployee); 
 

The same with the arrow operator is as below.

 var agedEmployee = employees.reduce((oldest,employee) => {return (oldest.Age || 0) > employee.Age ? oldest : employee  ;});
 console.log(agedEmployee); 
 

Here, the reduce method gets two parameters.

  • Oldest – A null value argument which is passed by me.
  • Employee – The object in the array.

 

  • During the first iteration, Oldest will be null, hence we are returning employee. This object, will become the first parameter (oldest) for the second iteration.
  • By that way, during the second iteration, the parameter ‘oldest’ will have {id:10, Age:30} and the parameter ‘employee’ will have {id:11, Age:27}

 

In case, If I want to add all the employees age, then the below will do that.

 var totalAge = employees.reduce((age,employee) => {
             return age + employee.Age; 
         },0);
 
         console.log(totalAge);
 

Here, the iteration will looks like,

IterationAgeEmployee.Age
1030
23027
35740

 

And the total would be 97.

Hope that helps and in the upcoming articles, we will see some other method.

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Refreshing JavaScript – Map Method – Detailed Explanation

Sathish Nadarajan
 
Solution Architect
April 26, 2019
 
Rate this article
 
Views
608

Refreshing JavaScript – A new Series which I am planning to write in depth about Javascript/JQuery methods, usages, samples in a simpler way.  As part of that, the first method, we focus today is MAP.

Definition:

.map() – A method which iterates through an array or collection and returns a new processed array.  The items in the array will be replaced with the manipulated item object.

Example:

I have an Array of Names.

 var arr = ["File1","File2","File3"]; 
         console.log(arr);
 
         var arr2 = arr.map(function(itm){
             return itm.toUpperCase();
         });
 
         console.log(arr2);
 

The output of the above code will be like,

 

In the original Array, the items are in the lower case and I want the items to be converted to Upper Case.  For that, either I can use the for or foreach loops as well.  But, in those cases, I need to declare the array.  Have a look on the below code.  The same is been implemented by for and foreach loops.

For Loop:

 var arrFor = [];
         for(i = 0;i<arr.length;i++)
         {
             arrFor.push(arr[i].toUpperCase());
         }
 
         console.log(arrFor);
 

For Each Loop:

 var arrForeach = [];
         arr.forEach(function(a){
             arrForeach.push(a.toUpperCase());
         });
 
         console.log(arrForeach);
 

In both the above methods, we need to initiate an array arrFor and arrForeach.  But, in the map method, we don’t need to declare any array.  The method returns an array and we can directly assign that to a array variable.

And moreover, with the arrow operator, the map method becomes very simple and clean.

 var arr = ["File1","File2","File3"]; 
         console.log(arr);
 
         var arr2 = arr.map(a => a.toUpperCase());
 
         console.log(arr2);
 

Hope that helps and in the upcoming articles, we will see some other method.

Happy Coding,

Sathish Nadarajan.

 

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Step by Step procedure to Create a Custom Action for Delete Button on SharePoint List Form Ribbon using JavaScript

Sriram
 
Technology Specialist
August 21, 2018
 
Rate this article
 
Views
5325

Recently I came up with requirement to change delete action’s confirmation message. Are you sure you want to send the item(s) to the Recycle Bin? to Are you sure you want to Cancel the Request? Also when clicking on the Delete icon, it should not delete the item; instead it should update the status of the item.

clip_image002

I have followed below approch to solve this problem.

Replace the ‘Delete Item’ button on the Ribbon bar with a copied ‘Delete Item’ button and then use ECMAScript and Sharepoint Client Object Model to remove the item and implement business logics.

Below are the steps to impelemet above functionality.

  1. Create 2 JS files for ViewForm and Edit Form,
  2. In the JS file under document.ready place the below code.

 

 $(document).ready(function(){
 //for view form
 var button = document.getElementById("Ribbon.ListForm.Display.Manage.DeleteItem-Medium");
 if (button != null) {
     var $button = $(button);
     var html = $button.html();
     $button.after("<div id='deleteIcon' OnMouseOver='ApplyCSSFunction()'><a style='cursor:pointer;'>" + html + "</a></div>").hide().next().click(function (e) {
 		DeleteCurrentItem();
     });
     $(".ms-cui-ctl-mediumlabel:eq(3)").css("vertical-align","top");
 	$(".ms-cui-ctl-mediumlabel:eq(3)").css("margin-left","4px");
 $('.ms-cui-ctl-mediumlabel:eq(3)').text("Cancel Request");
 	}
 
 $("#deleteIcon").mouseleave(function() {
  	  $("#deleteIcon").css("border-style","none");
         });
 });
 

 

  1. Write your business logic in DeleteCurrentItem() method.

 

 function DeleteCurrentItem()
 {
 $("#deleteIcon").css("border-style","none");
 var deleteConfirm = confirm("Are you sure you want to cancel this request?");
 if(deleteConfirm)
 {
  var deleteItemID=getParameterByName('ID');
  DeleteItem(deleteItemID);
 }
 }
 

 

  1. We need to change the highlighted line on the above code to make it work in Edit form.

View Form:

var button = document.getElementById(“Ribbon.ListForm.Display.Manage.DeleteItem-Medium”);

Edit Form:

var button = document.getElementById(“Ribbon.ListForm.Edit.Actions.DeleteItem-Large”);

Output:

clip_image004

Author Info

Sriram
 
Technology Specialist
 
Rate this article
 
Sriram T has been working in IT industry for over 6 years He holds Bachelor's degree in Computer Science Engineering. Sriram write articles and blogs related to SharePoint 2013, SharePoint ...read more
 

Leave a comment