Home > Net >  Concatenate elements of an array Javascript
Concatenate elements of an array Javascript

Time:03-02

I have a list of hrefs with product data:name and it's id. First of all i removed prod Id that i'll use as separate variable. After this, the remained part of href should be used as the product name.

var prodHref = document.querySelectorAll('.widget-products-list-item-label');
  var allHref = [];
   for(var i=0;i<prodHref.length;i  ){
  allHref.push(prodHref[i].href.split('/')[5])
  }
  var prodName = [];
   for(var i=0;i<allHref .length;i  ){
  prodName.push(allHref [i].slice(0, -1))
  }
  
  var prodNameNew=[];
  for(var i=0;i<prodName .length;i  ){
  prodNameNew.push(prodName[i].slice(0, -1))
  }

So, the final result is on the attached screen. N

How i have concatenate all the elements of each array in order to get new arrays in the following format: Nokia G20 4 64 Albastru, Motorola G60 gri etc Thank You

enter image description here

CodePudding user response:

You want to capitalize the items of the inner arrays and then join them by space.

One way to do it is:

let result = arr.map(a => a.map(capitalize))
  .map(a => a.join(" "))

where capitalize should be a function that takes a string and returns a string with first letter in upper case if possible. You can find this in answers for the more specific SO question: How do I make the first letter of a string uppercase in JavaScript?

CodePudding user response:

Instead of 3 separate loops, we can get the substring based on single iteration only using Array.map() along with String.slice().

const prodHref = [{
  href: "https://abc/def/ghi/alpha/mno"
}, {
  href: "https://abc1/def1/ghi1/beta/mno1"
}, {
  href: "https://abc2/def2/ghi2/gamma/mno2"
}, {
  href: "https://abc3/def3/ghi3/omicron/mno3"
}];

const allHref = prodHref.map((obj) => obj.href.split('/')[5].slice(0, -2));

console.log(allHref);

Now you can use Array.join() method to join the result array.

const allHref = ["alp", "be", "gam", "omicr"];

console.log(allHref.join(" "));

  • Related