Loop backward in array of objects JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have an array of objects like this −

let data = [
   {id:1, Name: "Abe", RowNumber: 1 },
   {id:2, Name: "Bob", RowNumber: 2 },
   {id:3, Name: "Clair", RowNumber: 3 },
   {id:4, Name: "Don", RowNumber: 3.0 },
   {id:5, Name: "Edna", RowNumber: 3.1 },
   {id:6, Name: "Frank", RowNumber: 3.2 },
   {id:7, Name: "Gabe", RowNumber: 4 },
   {id:8, Name: "Helen", RowNumber: 5 },
   {id:9, Name: "Isabelle", RowNumber: 6 },
   {id:10, Name: "Jane", RowNumber: 7 },
   {id:11, Name: "Ken", RowNumber: 8 },
];

We are required to write a JavaScript function that takes in this array and returns a string with names starting from last object right upto the first separated by ", "

Let's write the code for this function −

Example

const data = [
   {id:1, Name: "Abe", RowNumber: 1 },
   {id:2, Name: "Bob", RowNumber: 2 },
   {id:3, Name: "Clair", RowNumber: 3 },
   {id:4, Name: "Don", RowNumber: 3.0 },
   {id:5, Name: "Edna", RowNumber: 3.1 },
   {id:6, Name: "Frank", RowNumber: 3.2 },
   {id:7, Name: "Gabe", RowNumber: 4 },
   {id:8, Name: "Helen", RowNumber: 5 },
   {id:9, Name: "Isabelle", RowNumber: 6 },
   {id:10, Name: "Jane", RowNumber: 7 },
   {id:11, Name: "Ken", RowNumber: 8 },
];
const buildString = arr => {
   let str = '';
   for(let i = arr.length-1; i > -1; i--){
      str += `${arr[i]["Name"]}, `;
   };
   return str.substring(0, str.length-2);
};
console.log(buildString(data));

Output

The output in the console will be −

Ken, Jane, Isabelle, Helen, Gabe, Frank, Edna, Don, Clair, Bob, Abe
raja
Published on 31-Aug-2020 17:13:18
Advertisements