1

I have some values in a variable that could contain unknown number of arrays. for example,

digitalData.product[0] = "123";
digitalData.product[1] ="456";

and so on.

How is it possible to go through this arrays and then return the values? So, the desired output would be - 123;456;. Would the below work?

function range(start, count) {
    if (arguments.length == 1) {
        count = start;
        start = 0;
    }

    var foo = [];
    for (var i = 0; i < count; i++) {
        foo.push(start + i);
    }
    return digitalData.product.foo;
}

I would very much appreciate any help.

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Syed Haque
  • 13
  • 2

3 Answers3

0

if your desired output is like this - 123;456;789;

then you just have to join array with ";".

digitalData.product.join(";");

it will give you the same output what you want.

Arif Rathod
  • 578
  • 2
  • 13
  • So do you mean I just replace this line - return digitalData.product.foo with return digitalData.product.join(";"); – Syed Haque Sep 06 '18 at 11:48
  • yes, and remove all other code. remove that "range" function. now its not needed if you are going to use above method. var output = digitalData.product.join(";"); console.log(output); you will get result in output variable' – Arif Rathod Sep 06 '18 at 11:51
0

It should be:

digitalData = {};
digitalData ['product'] = ["123", "456"];

function range(arguments) {
    if (arguments.product.length == 1) {
        start = 0;
        count = start+1;
    } else{
        start = 0;
        count = arguments.product.length;
    }

    var foo = [];
    for (var i = 0; i < count; i++) {
        foo.push(arguments.product[start + i]);
    }
    return foo.toString();
}

console.log(range(digitalData));
protoproto
  • 2,081
  • 1
  • 13
  • 13
0

Just use slice to return the subarray you want. Don't worry about count going way beyond the end of the array as slice stops at the end of the array. Once you get that subarray, just join the results using or join(";"):

function range(start, count) {
    if (arguments.length == 1) {
        count = start;
        start = 0;
    }

    return digitalData.product.slice(start, start + count).join(";");
}

Example:

var digitalData = {
  product: ["aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg"]
};

function range(start, count) {
    if (arguments.length == 1) {
        count = start;
        start = 0;
    }

    return digitalData.product.slice(start, start + count).join(";");
}

console.log(`range(1, 3):     "${range(1, 3)}"`);
console.log(`range(2):        "${range(2)}"`);
console.log(`range(4, 10000): "${range(4, 10000)}"`);
console.log(`range(1000, 10): "${range(1000, 10)}"`);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73