<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shyamnath Vishwakarma on Medium]]></title>
        <description><![CDATA[Stories by Shyamnath Vishwakarma on Medium]]></description>
        <link>https://medium.com/@shyamnath?source=rss-14a6ee4374a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*T1ZGsLVItvt3Ky5q.jpg</url>
            <title>Stories by Shyamnath Vishwakarma on Medium</title>
            <link>https://medium.com/@shyamnath?source=rss-14a6ee4374a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:18:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shyamnath/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Go CLI Based ToDo App]]></title>
            <link>https://medium.com/@shyamnath/go-cli-based-todo-app-d37fb949c702?source=rss-14a6ee4374a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d37fb949c702</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[cli]]></category>
            <dc:creator><![CDATA[Shyamnath Vishwakarma]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 06:45:00 GMT</pubDate>
            <atom:updated>2023-08-29T06:45:00.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3v6oaSES_yZYxLz9" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we are going to create a CLI-based todo app that will store the todo’s in memory so let&#39;s get started</p><p>First, we will define a struct that will be used to represent the ToDo with just 2 fields an ID and a Label</p><pre>type ToDo struct {<br> Id    int    `json:&quot;id&quot;`<br> Label string `json:&quot;label&quot;`<br>}<br><br>func (t *ToDo) validate() error {<br> if t.Label == &quot;&quot; {<br>  return errors.New(&quot;Label can&#39;t be empty&quot;)<br> }<br> return nil<br>}</pre><p>Now its time to handle the in-memory storage of the todo’s for this we will use a map that will hold the id of the todo as the key and the ToDo object as a value</p><pre>package db<br><br>import (<br> &quot;github.com/shyam0507/to-do-cmd/model&quot;<br>)<br><br>type IMemory interface {<br> Add(*model.ToDo)<br> Update(*model.ToDo)<br> Delete(*model.ToDo)<br> GetById(id int) *model.ToDo<br> GetAll() []*model.ToDo<br>}<br><br>type memory struct {<br> mem     map[int]*model.ToDo<br> counter int<br>}<br><br>func New() IMemory {<br> return &amp;memory{mem: make(map[int]*model.ToDo), counter: 0}<br>}<br><br>func (m *memory) Add(t *model.ToDo) {<br> m.counter++<br> t.Id = m.counter<br> m.mem[t.Id] = t<br>}<br><br>func (m *memory) Update(t *model.ToDo) {<br> m.mem[t.Id] = t<br>}<br><br>func (m *memory) Delete(t *model.ToDo) {<br> delete(m.mem, t.Id)<br>}<br><br>func (m *memory) GetById(id int) *model.ToDo {<br> val, ok := m.mem[id]<br> if !ok {<br>  return nil<br> }<br> return val<br>}<br><br>func (m *memory) GetAll() []*model.ToDo {<br> var todos []*model.ToDo<br> for _, v := range m.mem {<br>  todos = append(todos, v)<br> }<br> return todos<br>}</pre><p>In the above code, we have defined an interface that has 5 methods and a struct of type memory to implement the methods</p><p>next step is to create a service to expose different methods that will internally use the memory db to store the todo’s</p><pre>package service<br><br>import (<br> &quot;errors&quot;<br><br> &quot;github.com/shyam0507/to-do-cmd/db&quot;<br> &quot;github.com/shyam0507/to-do-cmd/model&quot;<br>)<br><br>type ITodoService interface {<br> Add(*model.ToDo) (*model.ToDo, error)<br> Update(*model.ToDo) (*model.ToDo, error)<br> Delete(id int) error<br> GetById(id int) *model.ToDo<br> GetAll() []*model.ToDo<br>}<br><br>func NewService(db db.IMemory) ITodoService {<br> return &amp;toDoService{db: db}<br>}<br><br>type toDoService struct {<br> db db.IMemory<br>}<br><br>func (s *toDoService) Add(t *model.ToDo) (*model.ToDo, error) {<br> s.db.Add(t)<br> return t, nil<br>}<br><br>func (s *toDoService) Update(t *model.ToDo) (*model.ToDo, error) {<br> found := s.db.GetById(t.Id)<br> if found != nil {<br>  found.Label = t.Label<br>  s.db.Update(found)<br>  return found, nil<br> }<br> return nil, errors.New(&quot;Todo not found&quot;)<br>}<br><br>func (s *toDoService) Delete(id int) error {<br> found := s.db.GetById(id)<br> if found == nil {<br>  return errors.New(&quot;Todo not found&quot;)<br> }<br> s.db.Delete(s.db.GetById(id))<br> return nil<br>}<br><br>func (s *toDoService) GetById(id int) *model.ToDo {<br> return s.db.GetById(id)<br>}<br><br>func (s *toDoService) GetAll() []*model.ToDo {<br> return s.db.GetAll()<br>}</pre><p>Similar to the in-memory db the todo service also has 5 methods to perform different CRUD operations on the todo’s. now let&#39;s write the main.go file and use the service to store the todo’s</p><p>main file will use the Scanner function to get the command from the user validate the command the then store the data in the memory using the todo service</p><pre>func main() {<br> log.Print(&quot;Start the todo app...&quot;)<br><br> ser := service.NewService(db.New())<br><br> scanner := bufio.NewScanner(os.Stdin)<br><br> for {<br>  scanner.Scan()<br>  cmd := strings.Split(scanner.Text(), &quot; &quot;)<br><br>  // log.Printf(&quot;Operation %s&quot;, cmd[0])<br>  switch strings.ToLower(cmd[0]) {<br>  case &quot;add&quot;:<br>   ser.Add(&amp;model.ToDo{Label: strings.Join(cmd[1:], &quot; &quot;)})<br>  case &quot;delete&quot;:<br>   id, err := strconv.Atoi(cmd[1])<br>   if err != nil {<br>    fmt.Printf(&quot;Please provide a valid Id - %v\n&quot;, id)<br>    continue<br>   }<br>   if err := ser.Delete(id); err != nil {<br>    fmt.Printf(&quot;Id %d not found\n&quot;, id)<br>   }<br>  case &quot;update&quot;:<br>   id, err := strconv.Atoi(cmd[1])<br>   if err != nil {<br>    fmt.Printf(&quot;Please provide a valid Id - %v\n&quot;, id)<br>    continue<br>   }<br>   ser.Update(&amp;model.ToDo{Id: id, Label: strings.Join(cmd[2:], &quot; &quot;)})<br>  case &quot;get&quot;:<br>   id, err := strconv.Atoi(cmd[1])<br>   if err != nil {<br>    fmt.Printf(&quot;Please provide a valid Id - %v\n&quot;, cmd[1])<br>    continue<br>   }<br>   todo := ser.GetById(id)<br>   if todo == nil {<br>    fmt.Printf(&quot;todo with id :%d not found\n&quot;, id)<br>   } else {<br>    fmt.Printf(&quot;%d    %s\n&quot;, todo.Id, todo.Label)<br>   }<br>  case &quot;getall&quot;:<br>   todos := ser.GetAll()<br>   if len(todos) == 0 {<br>    fmt.Printf(&quot;No Todo&#39;s available\n&quot;)<br>    continue<br>   }<br>   for _, todo := range todos {<br>    fmt.Printf(&quot;%d    %s\n&quot;, todo.Id, todo.Label)<br>   }<br>  default:<br>   fmt.Printf(&quot;Invalid operation %s&quot;, cmd[0])<br>  }<br><br> }<br><br>}</pre><p>Now if we run the main.go file we can perform different CRUD operations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-SJIfgMd9G3sX4GI4-77Q.png" /></figure><p>The complete source code of the project is available on <a href="https://github.com/shyam0507/go-todo-cli">GitHub</a>.</p><p>Thanks for reading! I hope you find this article useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d37fb949c702" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC with Go and Node.Js]]></title>
            <link>https://medium.com/@shyamnath/grpc-with-go-and-node-js-f80a958d1055?source=rss-14a6ee4374a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f80a958d1055</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Shyamnath Vishwakarma]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 07:04:02 GMT</pubDate>
            <atom:updated>2023-02-05T07:04:02.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pyoxFOXBlS8eQv-C" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>gRPC is a modern open source high performance Remote Procedure Call (RPC) framework that can run in any environment this is used to build scalable and fast APIs</p><p>This framework relies on HTTP/2 and protocol buffers it works across languages and platforms. In this article, we will see how two services built using different languages Go and Node.JS communicate via gRPC</p><p>gRPC supports multiple streaming options, in this article, we will use the server to client streaming</p><ol><li>Unary (no streaming)</li><li>Client-to-server streaming</li><li>Server-to-client streaming</li><li>Bi-directional streaming</li></ol><p><strong>Project Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rodi4tp6xq-c9rc2K1Yt4Q.png" /></figure><p>We will create two services</p><ol><li>Review Service — this will be built using GO and this will store reviews of the movies</li><li>Movie Service — this will be built using node.js and this will store movies</li></ol><p>these two services will communicate with each other using gRPC when a user asks for a movie using the id of the movie, movie service will call Review Service via gRPC and get all the reviews of the particular movie and then return the response back to the user along with the movie information</p><p><strong>Review Service — </strong>let&#39;s start with the review service first in this we will create the gRPC server, and we will build this service using go, first let&#39;s create a .proto file, this file will contain the service and message definition that will be used for communication between the services</p><pre>syntax = &quot;proto3&quot;;<br><br>package review;<br><br>option go_package=&quot;&quot;;<br><br>message ReviewRequest {<br>    string id = 1;<br>} <br><br>message ReviewResponse {<br>    string id = 1;<br>    string review = 2;<br>    float rating = 3;<br>}<br><br>service ReviewService {<br>    rpc GetGreeting (ReviewRequest) returns (stream ReviewResponse);<br>}</pre><p>to generate the relevant proto files for the review service in GO we will use the below command</p><pre>protoc --go_out=. --go_opt=module=github.com/shyam0507/grpc-node-go \<br>    --go-grpc_out=. --go-grpc_opt=module=github.com/shyam0507/grpc-node-go \<br>    proto/review.proto</pre><p>after running the command two go files review_grpc.pb.go and review.pb.go will be generated inside the proto folder, in the review_grpc.pb.go file we have an interface ReviewServiceServer which has a function called GetReviews, we need to implement the function to return the reviews of a movie</p><pre>type Review struct {<br> Id      int32   `json:&quot;id&quot;`<br> MovieId int32   `json:&quot;movie_id&quot;`<br> Review  string  `json:&quot;review&quot;`<br> Rating  float32 `json:&quot;rating&quot;`<br>}<br><br>func (s *Server) GetReviews(req *pb.ReviewRequest, stream pb.ReviewService_GetReviewsServer) error {<br> ratings := readData(req.Id)<br> for i := 0; i &lt; len(ratings); i++ {<br>  stream.Send(&amp;pb.ReviewResponse{Id: ratings[i].Id, Review: ratings[i].Review, Rating: ratings[i].Rating})<br> }<br> return nil<br>}<br><br>func readData(id int32) []Review {<br> content, err := ioutil.ReadFile(&quot;./data/ratings.json&quot;)<br><br> if err != nil {<br>  log.Fatalf(&quot;Error while reading the file!&quot;)<br> }<br><br> var allReviews []Review<br> err = json.Unmarshal(content, &amp;allReviews)<br> if err != nil {<br>  log.Fatal(&quot;Error while parsing the file!&quot;, err)<br> }<br> var reviews []Review<br> for _, v := range allReviews {<br>  if v.MovieId == id {<br>   reviews = append(reviews, v)<br>  }<br> }<br><br> return reviews<br>}</pre><p>In the above code, we have implemented the function GetReviews which will return a list of reviews for a movie, the readData function reads the reviews from a JSON file and returns the reviews.</p><p><strong>Movie Service —</strong> We have the gRPC server running with the review service now its time to create the movie service which will call the GetReviews() function of the review service to fetch all the reviews of a movie, for node.js we do not need to generate any specific code to work with gRPC we will only need the .proto file that we created earlier</p><pre>const grpc = require(&quot;@grpc/grpc-js&quot;);<br>var protoLoader = require(&quot;@grpc/proto-loader&quot;);<br>const PROTO_PATH = &quot;./proto/review.proto&quot;;<br><br>const options = {<br>  keepCase: true,<br>  longs: String,<br>  enums: String,<br>  defaults: true,<br>  oneofs: true,<br>};<br><br>var packageDefinition = protoLoader.loadSync(PROTO_PATH, options);<br><br>const ReviewService =<br>  grpc.loadPackageDefinition(packageDefinition).review.ReviewService;<br><br>const client = new ReviewService(<br>  &quot;0.0.0.0:50051&quot;,<br>  grpc.credentials.createInsecure()<br>);<br><br>const getReviews = async (movieId) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    ratings = [];<br>    const stream = client.GetReviews({ id: movieId });<br><br>    stream.on(&quot;data&quot;, function (data) {<br>      console.log(data);<br>      ratings.push(data);<br>    });<br><br>    stream.on(&quot;end&quot;, function () {<br>      resolve(ratings);<br>    });<br><br>    stream.on(&quot;error&quot;, () =&gt; {<br>      reject(&quot;&quot;);<br>    });<br>  });<br>};<br><br>module.exports = getReviews;</pre><p>in the above code, we have the getReviews function which is calling the gRPC server to fetch the review, the server return stream of reviews which is collected in an array, and once all the reviews are received the function returns the array</p><p>Movie service will expose a REST endpoint to fetch movie details, now let&#39;s create a REST API endpoint to expose movie information</p><pre>const express = require(&quot;express&quot;);<br>const getReviews = require(&quot;./grpc&quot;);<br><br>const getMovie = require(&quot;./utils&quot;);<br>app = express();<br><br>const PORT = 3000;<br><br>app.get(&quot;/health&quot;, async (req, res) =&gt; {<br>  console.log(&quot;Health API was called&quot;);<br>  res.send({ message: &quot;service is up&quot; });<br>});<br><br>app.get(&quot;/movies/:id/reviews&quot;, async (req, res) =&gt; {<br>  try {<br>    const movieId = req.params.id;<br>    console.log(&quot;Movie ratings API was called&quot;, movieId);<br><br>    const movie = await getMovie(movieId);<br>    const ratings = await getReviews(movieId);<br>    res.send({ ...movie, ratings: [...ratings] });<br>  } catch (error) {<br>    res.status(400).send({ message: &quot;error&quot; });<br>  }<br>});<br><br>app.listen(PORT, () =&gt; {<br>  console.log(&quot;movie service running on port&quot;, PORT);<br>});</pre><p>in the above code, we are exposing a GET API to get the movie information, we first get the movie data like the name from the movie service and then call the review service to fetch the reviews of the movie using gRPC and then return the response back to the caller</p><p>The complete source code of the project is available on <a href="https://github.com/shyam0507/grpc-node-go">GitHub</a>.</p><p>Thanks for reading! I hope you find this article useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f80a958d1055" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka with Node.Js]]></title>
            <link>https://medium.com/@shyamnath/kafka-with-node-js-eaddb1048b5a?source=rss-14a6ee4374a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaddb1048b5a</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kafkajs]]></category>
            <dc:creator><![CDATA[Shyamnath Vishwakarma]]></dc:creator>
            <pubDate>Sun, 10 Jul 2022 14:27:13 GMT</pubDate>
            <atom:updated>2022-07-10T14:27:13.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cxpk-wIoW4HosU0y" /><figcaption>Photo by <a href="https://unsplash.com/@er1end?utm_source=medium&amp;utm_medium=referral">Erlend Ekseth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Kafka is one of the very efficient and popular event/message steaming platforms for building microservices-based software applications, Kafka can work as the backbone of your microservices so that different microservices can communicate with each other in an asynchronous fashion.</p><p><strong>Integration with Node.JS</strong> — We are going to create a simple node.js application to consume data from Wikimedia event stream <a href="https://stream.wikimedia.org/v2/stream/recentchange">API </a>and put it inside a Kafka Topic using a producer and then read the data from Kafka and store it inside ElasticSearch. below is the HLD of the sample application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81CBHWAOVp7Si6Rmq81pdQ.png" /><figcaption>HLD of project</figcaption></figure><p>To work with Kafka we will be using the NPM module <a href="https://www.npmjs.com/package/kafkajs">KafkaJS</a> and to listen to the event stream we will use <a href="https://www.npmjs.com/package/eventsource">eventsource </a>module so let&#39;s get started</p><p>First, we will create a node project and install npm modules</p><p>npm i eventsource kafkajs</p><p>Our Project is ready now let&#39;s start with listening to the Wikimedia stream</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1c0ecf65ef671b364ed93d40a56c051/href">https://medium.com/media/b1c0ecf65ef671b364ed93d40a56c051/href</a></iframe><p>the above code will listen to the Wikimedia stream and then when a message is received it will log in to the console, next step is to send the event inside Kafka so let&#39;s write our producer</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8df82e8cfe726c534b495daf0f426af7/href">https://medium.com/media/8df82e8cfe726c534b495daf0f426af7/href</a></iframe><p>We can use the above producer to send a message to Kafka using the following code, we will use it inside our main file</p><pre>await producer.send({<br>   topic: &#39;wikimedia.recentchanges&#39;,<br>   messages: [{ value: JSON.stringify(payload) }],<br>});</pre><p>With producer setup being done now its time to build our consumer which will consume the message publisher on ‘wikimedia.recentchanges’ topic from Kafka</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/830e32034b255fc06c0f0741debf250b/href">https://medium.com/media/830e32034b255fc06c0f0741debf250b/href</a></iframe><p>Now our producer and consumer are ready let&#39;s create an index file to run both producer and consumer</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8894e3d66ccb44f63a0ada80d494fda/href">https://medium.com/media/b8894e3d66ccb44f63a0ada80d494fda/href</a></iframe><p>if you run our main file you will see that we are successfully able to send and consume messages to and from Kafka, now let’s save the message inside ElasticSearch.</p><p>To work with elastic search we will be using the npm module <a href="https://www.npmjs.com/package/@elastic/elasticsearch">@elastic/elasticsearch</a> let&#39;s change our main file to save Wikimedia changes to elastic search</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc8877731b3701adc14467dd7b0b9107/href">https://medium.com/media/fc8877731b3701adc14467dd7b0b9107/href</a></iframe><p>Now if you run the main file and open Kibana you will see the documents are getting indexed inside ElasticSearch index ‘wikimedia_recentchanges’</p><p>The complete source code of the project is available on <a href="https://github.com/shyam0507/wikimedia-kafka-elastic">Github</a>.</p><p>Thanks for reading! I hope you find this article useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaddb1048b5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript map(), reduce() and filter()]]></title>
            <link>https://medium.com/@shyamnath/javascript-map-reduce-and-filter-1c2fa474c742?source=rss-14a6ee4374a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c2fa474c742</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Shyamnath Vishwakarma]]></dc:creator>
            <pubDate>Sun, 10 Oct 2021 11:16:59 GMT</pubDate>
            <atom:updated>2021-10-10T11:16:59.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xd3oY6fUSYpNVYa2" /><figcaption>Photo by <a href="https://unsplash.com/@seanstratton?utm_source=medium&amp;utm_medium=referral">Sean Stratton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In javascript, there are three important methods available to work with an array let’s go through them one by one.</p><p><strong>map()</strong></p><p>the map() is used to create a new array from an existing array you can apply a function on each element of the existing array and based upon the result of the applied function on each element of the array a new array is created.</p><pre>const myArray = [10, 20, 30, 40, 50];</pre><pre>//create a new array by multiplying each element of myArray by 2</pre><pre>const newArray = myArray.map(item=&gt;item*2);</pre><pre>console.log(newArray); // output [20, 40, 60, 80, 100]</pre><p><strong>reduce()</strong></p><p>The reduce() method is used to reduce an array to a single value, your can supply a reducer function which will be applied on each element of the array passing the calculation of each element to the next element of the array, and in the end, a final result will be returned.</p><pre>const myArray = [10, 20, 30, 40, 50];</pre><pre>//find the sum of all elements of the array</pre><pre>const sumValue = myArray.reduce((totalVal,curVal)=&gt;totalVal+curVal);</pre><pre>console.log(sumValue); // output 150</pre><p>in the above example, the <strong>totalVal</strong> is an accumulator and its values can be initialized before running the reduce().</p><pre>const myArray = [10, 20, 30, 40, 50];</pre><pre>//find the sum of all elements of the array, initalize the totalValue with 150</pre><pre>const sumValue = myArray.reduce((totalVal,curVal)=&gt;totalVal+curVal, <strong>150</strong>);</pre><pre>console.log(sumValue); // output 300</pre><p><strong>filter()</strong></p><p>the filter() method is used to filter the given array using a conditional statement, if the condition returns true for a particular item of the array then that item is returned to the output array otherwise it&#39;s skipped.</p><pre>const myArray = [10, 20, 30, 40, 50];</pre><pre>//filter the array with by removing elements with value less than 20</pre><pre>const filteredArray = myArray.filter((value)=&gt;value&gt;20);</pre><pre>console.log(filteredArray); // output [30, 40, 50]</pre><p>Thanks for reading! I hope you find this article useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c2fa474c742" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>