0

How to recover the elements of a foreach for reformed in this way:

['julie','nicola','sahra']

My code

   var outPutStats = ''
    client.data.forEach(function(element) {
         outPutStats += [element.name];
    }); 
    .............................
    .............................

        xAxis: {
            name: [outPutStats] // Must be ['dataName1','dataName2']
        },
        yAxis: {
            title: {
                text: null
            }
        },  
6
  • what's client.data look like? Commented Jan 28, 2017 at 2:01
  • do you want outPutStats to be an array or a string? Commented Jan 28, 2017 at 2:03
  • @Paul is a array, one by one name is client.torrents[0].name Commented Jan 28, 2017 at 2:04
  • @ibrahimmahrir In string I supose, it must come out in this way: ['julie','nicola','sahra'] Commented Jan 28, 2017 at 2:05
  • @atmon3r I don't follow. You want the outPutStats to be like this: ['julie','nicola','sahra'] or like this "['julie','nicola','sahra']"? Commented Jan 28, 2017 at 2:08

2 Answers 2

1

try this:

var outputStats = [];
client.data.forEach(function(element) { 
  outputStats.push(element.name);
});

It's probably more semantically accurate to use Array#map instead, though, if the clients you want support it (which afaik they should if they support forEach):

var outputStats = client.data.map(function(element) { return element.name; });
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to copy client.data into a new array outPutStats then this will work (although I don't see the reason why, you could just use client.data):

// This must be an array
var outPutStats = [];
client.data.forEach(function(element) {
    // fill the array with elements
    outPutStats.push(element.name);
}); 
// ...
// ...

xAxis: {
    name: outPutStats // outPutStats is already an array
},
    yAxis: {
        title: {
            text: null
        }
    },  

3 Comments

He's trying to transform the array content, is why he is not just using client.data.
@torazaburo Why poor? It does the same thing. Plus I just keeped the same format as the question. (he used forEach so I used it as well to keep things clear).
This use case is the entire raison d'etre of map. And yes, you are allowed, indeed encouraged, to suggest ways to improve the OP's code, rather than slavishly copy sub-optimal parts of it.

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.