↓ Skip to main content
Web & APIs

JS Reduce and forEach

·3 mins
Table of Contents
Matrix

I have been polishing my Go and JS skills recently and today learned about how to use the reduce() and forEach() method. The problem I was trying to solve was return columns and rows from an input string.

A new line separator is used to define a new row and for each element is separated by ‘ ‘.

I started off with a basic class (code below)

export class Matrix {
  constructor(matrix) {}
}

The matrix is the input string that we shall be using to populate rows and columns.

Parsing
#

Rows
#

this.rows = matrix.split('\n')
      .map(row => row.split(' ')
      .map(r => +r));

Parsing rows was relatively simple, I used the map method to find individual element and convert it to a number. (Numeric representation), if numeric is not required a simple split should do.

Columns
#

1.  this.columns = this.rows.reduce(
2.  (columns, row, i) => {
3.   row.forEach((current, j) => {
4.   if (i===0) {
5.    columns.push([row[j]]);
6.   } else {
7.    columns[j].push(current);
8.   }
9.  });
10.  return columns;
11. }, []);

In row 1. I simply invoked reduce() method on rows which we parsed in the step above.

The reducer function takes four arguments:

  1. Accumulator (acc)
  2. Current Value (cur)
  3. Current Index (idx)
  4. Source Array (src)

Your reducer function’s returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value.

(columns, row, i)

We intent to return the columns which shall have the individual column read from the array of rows. Each ‘row’ will be representation of one such row [ ] and ‘i’ is the index.

If there are 3 rows that were read. e.g. [0,1,2],[3,4,5],[5,6,7] the i will iterate through 0..2

For each row that we get in step 2, we will iterate through the individual elements within that row to be added to column array (forEach).

forEach is taking two arguments

(current, j)
Current -> Identifies the value being processed.
j       -> Identifies the index.

The processing is done between line 4 – 8.

So if we consider an example

    0 1 2
--------------
0 | 1 2 3 \n
1 | 4 5 6 \n
2 | 7 8 9 \n

So the rows get populated as

row = [
    rows[0] = [1, 2, 3]
    rows[1] = [4, 5, 6]
    rows[2] = [7, 8, 9]
]

So, the processing of line 4 – 8

row +> 1, 2 ,3 & i =0
The first iteration starts at
current = 1, j = 0

Line 4. since i = 0
columns[0] = 1
The loop repeats
columns[1] = 2
The loop repeats
columns [2] = 3
The outer loop repeats
row +> 4, 5 ,6 & i =1
current = 4, j = 0

& the same way the logic repeats.

Finally you will have columns

columns = [[1,4,7], [2, 5, 8], [3, 6, 9]]

– THE – END –

Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Optimizing in JS

·2 mins
You never stop learning is not just a phrase, it is something I live everyday. Today, I was just trying out my skills with JS and was solving an innocuous problem, in JS.

MySQL/MariaDB on MAC

·1 min
Challenges are plenty but outcome is always one – Learning! While trying to troubleshoot an inhouse application I had to setup a quick MySQL instance which led me to install my first instance of MariaDB on my local MAC machine.

KubeLab

·3 mins
Kubernetes cloud_user@ip-10-0-1-101:~$ kubectl version Client Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.3", GitCommit:"721bfa751924da8d1680787490c54b9179b1fed0", GitTreeState:"clean", BuildDate:"2019-02-01T20:08:12Z", GoVersion:"go1.11.5", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.11", GitCommit:"25074a190ef2a07d8b0ed38734f2cb373edfb868", GitTreeState:"clean", BuildDate:"2019-09-18T14:34:46Z", GoVersion:"go1.11.13", Compiler:"gc", Platform:"linux/amd64"} cloud_user@ip-10-0-1-101:~$ kubectl api-resources NAME SHORTNAMES APIGROUP NAMESPACED KIND bindings true Binding componentstatuses cs false ComponentStatus configmaps cm true ConfigMap endpoints ep true Endpoints events ev true Event limitranges limits true LimitRange namespaces ns false Namespace nodes no false Node persistentvolumeclaims pvc true PersistentVolumeClaim persistentvolumes pv false PersistentVolume pods po true Pod podtemplates true PodTemplate replicationcontrollers rc true ReplicationController resourcequotas quota true ResourceQuota secrets true Secret serviceaccounts sa true ServiceAccount services svc true Service mutatingwebhookconfigurations admissionregistration.k8s.io false MutatingWebhookConfiguration validatingwebhookconfigurations admissionregistration.k8s.io false ValidatingWebhookConfiguration customresourcedefinitions crd,crds apiextensions.k8s.io false CustomResourceDefinition apiservices apiregistration.k8s.io false APIService controllerrevisions apps true ControllerRevision daemonsets ds apps true DaemonSet deployments deploy apps true Deployment replicasets rs apps true ReplicaSet statefulsets sts apps true StatefulSet tokenreviews authentication.k8s.io false TokenReview localsubjectaccessreviews authorization.k8s.io true LocalSubjectAccessReview selfsubjectaccessreviews authorization.k8s.io false SelfSubjectAccessReview selfsubjectrulesreviews authorization.k8s.io false SelfSubjectRulesReview subjectaccessreviews authorization.k8s.io false SubjectAccessReview horizontalpodautoscalers hpa autoscaling true HorizontalPodAutoscaler cronjobs cj batch true CronJob jobs batch true Job certificatesigningrequests csr certificates.k8s.io false CertificateSigningRequest leases coordination.k8s.io true Lease events ev events.k8s.io true Event daemonsets ds extensions true DaemonSet deployments deploy extensions true Deployment ingresses ing extensions true Ingress networkpolicies netpol extensions true NetworkPolicy podsecuritypolicies psp extensions false PodSecurityPolicy replicasets rs extensions true ReplicaSet networkpolicies netpol networking.k8s.io true NetworkPolicy poddisruptionbudgets pdb policy true PodDisruptionBudget podsecuritypolicies psp policy false PodSecurityPolicy clusterrolebindings rbac.authorization.k8s.io false ClusterRoleBinding clusterroles rbac.authorization.k8s.io false ClusterRole rolebindings rbac.authorization.k8s.io true RoleBinding roles rbac.authorization.k8s.io true Role priorityclasses pc scheduling.k8s.io false PriorityClass storageclasses sc storage.k8s.io false StorageClass volumeattachments storage.k8s.io false VolumeAttachment cloud_user@ip-10-0-1-101:~$ kubectl get cm NAME DATA AGE fruit-service-ambassador-config 1 5m49s Basic Commands (Beginner): create Create a resource from a file or from stdin. expose Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service run Run a particular image on the cluster set Set specific features on objects Basic Commands (Intermediate): explain Documentation of resources get Display one or many resources edit Edit a resource on the server delete Delete resources by filenames, stdin, resources and names, or by resources and label selector Deploy Commands: rollout Manage the rollout of a resource scale Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job autoscale Auto-scale a Deployment, ReplicaSet, or ReplicationController Cluster Management Commands: certificate Modify certificate resources. cluster-info Display cluster info top Display Resource (CPU/Memory/Storage) usage. cordon Mark node as unschedulable uncordon Mark node as schedulable drain Drain node in preparation for maintenance taint Update the taints on one or more nodes Troubleshooting and Debugging Commands: describe Show details of a specific resource or group of resources logs Print the logs for a container in a pod attach Attach to a running container exec Execute a command in a container port-forward Forward one or more local ports to a pod proxy Run a proxy to the Kubernetes API server cp Copy files and directories to and from containers. auth Inspect authorization Advanced Commands: diff Diff live version against would-be applied version apply Apply a configuration to a resource by filename or stdin patch Update field(s) of a resource using strategic merge patch replace Replace a resource by filename or stdin wait Experimental: Wait for a specific condition on one or many resources. convert Convert config files between different API versions Settings Commands: label Update the labels on a resource annotate Update the annotations on a resource completion Output shell completion code for the specified shell (bash or zsh) Other Commands: api-resources Print the supported API resources on the server api-versions Print the supported API versions on the server, in the form of "group/version" config Modify kubeconfig files plugin Provides utilities for interacting with plugins. version Print the client and server version information Usage: kubectl [flags] [options]