Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add some text to start and end of each element in an array

I have an array. I want to add some characters (:,\n) to each element in that array to be shown in a text box.

Currently this is what I'm doing

$scope.source.arr = .... //This is an array
var actualText = "";

function func() {
    $scope.source.arr.forEach(function(ele){
        actualText += "***" + ele + " - \n"; //Adding necessary characters
    })
}

var showText = function() {
    func(); //Calling the function that populates the text as needed
    var textBox = {
          text : actualText; 
          ...
     }
}

Is there a better way to do this?

like image 992
user7 Avatar asked Dec 27 '25 16:12

user7


2 Answers

You can simply use Array.prototype.map to create a new Array object with the changed strings, like this

var textBox = {
      text: $scope.source.arr.map(function(ele) {
          return "***" + ele + " -  ";
      }).join("\n"),
      ...
 };

For each element in the arr, we are creating a new string corresponding to it and creating an array of strings. Finally we join all the strings in the array with \n.

like image 57
thefourtheye Avatar answered Dec 30 '25 04:12

thefourtheye


You can use Array.prototype.map, Array.prototype.reduce to make it better.

Check reduce function here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

var prefix = "***";
var postfix = "$$$";

var targetStrArr = ["apple", "banana"]

var resultStr = targetStrArr.map(function(ele){
    return prefix + ele + postfix; //Adding necessary characters
}).reduce(function(prevVal, curVal) {
    return prevVal + curVal;
});

console.log(resultStr); // ***apple$$$***banana$$$
like image 30
Hee Jae Kim Avatar answered Dec 30 '25 06:12

Hee Jae Kim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!