0

Given these two arrays:

$scope.city= [{id :'NewYork' } , {id : 'Chicago'}];
$scope.color = [{id : 'blue' } , {id : 'Green'}];

I need only the values of both arrays like this:

$scope.string = 'NewYork_Chicago_blue_Green';

4 Answers 4

4

Use Array#map to convert each array to an array of strings, then Array#concat them, and Array#join with underscore:

var city = [ {id :'NewYork' } , {id : 'Chicago'}];
var color = [{id : 'blue' } , {id : 'Green'}];

function getId(o) {
  return o.id;
}

var result = city.map(getId).concat(color.map(getId)).join('_');

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

2

You could do that using forEach:

    $scope.constructString = function(arr){
        arr.forEach(function(item){
        if($scope.string && $scope.string.length>0)
            $scope.string += '_';
        $scope.string +=  item.id;
    });

    $scope.constructString($scope.city);
    $scope.constructString($scope.color);

Comments

0

One other way of doing the job could be;

var city = [{id : 'NewYork'}, {id : 'Chicago'}],
   color = [{id : 'blue'}, {id : 'Green'}];
  result = city.concat(color)
               .reduce((p,c,i) => i-1 ? p    + "_" + c.id
                                      : p.id + "_" + c.id);
console.log(result);

Comments

0

Try these steps :

  • Array concat() method - used to merge two or more arrays.
  • Array join() method - joins all elements of an array into a string.

Working demo :

var city= [ {id :'NewYork' } , {id : 'Chicago'}];

var color = [{id : 'blue' } , {id : 'Green'}];

var cityColor = city.concat(color);

var arr = [];

for (var i in cityColor) {
  arr.push(cityColor[i].id);
}

var str = arr.join('_');

console.log(str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.