0

I called a function to count, and I would like to return the data as an array and use it then, how can I do the same . where this returned arr is been stored, so I can use t in main code

var newArr =[]
    countData(jsonData).then(function (res) {
        console.log(arr)
        console.log('end')
    })

    function countData(jsonData){
        var five=0, two =0
        for(var i in jsonData){
            console.log(jsonData)
            if(jsonData.num == '5'){
                five++;
            }
            else{
                two++;
            }
        }//for
        var arr =[]
        arr[0]=five
        arr[1]=two
        return arr
    }//function
1

1 Answer 1

2

The return value of countData is an array.

It isn't a Promise. The doesn't have a then method. Just use the return value directly.

const data = {
  "num": "2",
  "num": "5",
  "num": "5",
  "num": "2",
  "num": "2",
  "num": "2"
}
const result = countData(data);
console.log(result);

function countData(jsonData) {
  var five = 0,
    two = 0
  for (var i in jsonData) {
    console.log(jsonData)
    if (jsonData.num == '5') {
      five++;
    } else {
      two++;
    }
  } //for
  var arr = []
  arr[0] = five
  arr[1] = two
  return arr
} //function

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

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.