1

The JSON:

[{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
{"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
{"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}]

The JavaScript:

jQuery.ajax({
    url: "file.json",
    type: "POST",
    dataType: "json",
    async: false,
    success: function (data) {
    var arr = [];
    for (i = 0; i < data.length; i++) { 
        arr.push(data[i].answer);
    }
    console.log(arr);
});

What I'm trying to do is make an average of each value from the 3 answers, which in case will give these 8 averages:

2,3,3,3,2,1,3,2
8
  • 3
    How are you trying? Can we see an attempt? Commented Feb 25, 2018 at 14:23
  • I was making a split, with an each, and putting in array again, which was returning in front, not over numbers like ["123","123456","123456789"]. I dont considered useful posting this :/ Commented Feb 25, 2018 at 14:39
  • Can you share input and output? Commented Feb 25, 2018 at 14:44
  • 1
    The reason you're getting numbers like this ["123","123456","123456789"] is that you're adding strings, so they add like characters next to each other. To add them mathematically as values, you need to convert them to numbers first. Commented Feb 25, 2018 at 14:45
  • 2
    I'd consider showing that code in your post very useful. It doesn't need to be correct, but it shows you really have tried something, and also most likely makes the goal more clear. Unless I haven't misunderstood your question, some answerers seem to have, despite of some very beautiful code in answers. Commented Feb 25, 2018 at 14:57

4 Answers 4

1

const arrAvg = arr => arr.reduce((a,b) => a + b, 0) / arr.length;
console.log(arrAvg([1,2,3,4,5]));

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

Comments

1

create a new array from the answer then sum all the values and divide by its size

var res = [{
    "id": "1",
    "user": "001",
    "answer": "1,1,3,2,2,1,3,2"
  },
  {
    "id": "2",
    "user": "002",
    "answer": "2,3,3,2,1,1,3,2"
  },
  {
    "id": "3",
    "user": "003",
    "answer": "3,5,3,5,3,1,3,2"
  }
];
res.forEach(function(item) {
  //creating array from the string
  var imtArray = item.answer.split(',');
  //summing the element
  var avg = imtArray.reduce(function(p, q) {
    // converting string to number
    return +p + +q
  })
  console.log(avg / imtArray.length)


})

Comments

1

You may use:


Working Example:

let data = [{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
            {"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
            {"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}];

let result = data.map(o => {
  /* Split the string into array using , delimiter */
  let a = o["answer"].split(",");
  /*
   * Return average of array by first creating sum using .reduce() and
   * then dividing by number of array elements.
   */
  return a.reduce((a,c) => (Number(c) + a), 0) / a.length;
});

console.log(result);

Comments

0

You're getting the answer, but now you need to split it by commas and parse it to a number. This gives you an array for each answer, now you can simply iterate through each one and add the numbers then divide them by their count (i.e. array length) to calculate the average.

Note: the values in the answers are strings, so make sure you convert them to numbers before you add them together, otherwise you will be adding them together as characters.

var data = [{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
            {"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
            {"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}]

var arr = [];
for (var i = 0; i < data.length; i++) {
  var d = data[i].answer.split(",");
  var sum = 0;
  for (var j = 0; j < d.length; j++) {
    sum += parseInt(d[j]);
  }
  arr.push(sum / d.length);
}
console.log(arr);

It seems from your comments that instead of the average of values in each of the three answers, you actually want the average of each value from the three answers. Similar to the code above, you just need to make a little change. You'll have to iterate and add the values of each answer first, then iterate again and calculate the averages:

var data = [{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
            {"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
            {"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}]

var arr = [];
for (var i = 0; i < data.length; i++) {
  var d = data[i].answer.split(",");
  for (var j = 0; j < d.length; j++) {
    d[j] = parseInt(d[j]);
  }
  if (arr.length == 0)
    arr = d;
  else {
    for (var j = 0; j < d.length; j++) {
      arr[j] += d[j];
    }
  }
}
for (var i = 0; i < arr.length; i++) {
  arr[i] = arr[i] / data.length;
}
console.log(arr);

Note: This assumes that each answer has the exact same number of values.

5 Comments

Serious, thank you very much! I was losing my hair and my health to this. God bless you!
This is a really unnecessarily complicated answer for something made in 2018. It also gives a lot of bad practices such as using var
@Treycos What does 2018 have anything to do with the answer? The answer was based on the question. If you feel that it was "unnecessarily complicated" and you have a better answer, why don't you post it instead of downvoting a correct and accepted answer almost a year later. And since when was using var a bad practice? There is nothing wrong with var if used correctly.
This answer is written using JavaScript practices from more than 5 years ago. Why would voting be based on the date the answer was posted ? Using var is an extremely bad practice to adopt when starting to code in JS because they aren't respecting any scope and are equivalent of global variables no matter where they are declared in your code. Also, the variables names make the code unreadable. Yes, I do have a better answer, the one right below, a few lines, easily readable, clear, this is the correct answer. If you do care about developers starting out with JS, I recommend deleting yours.
@Treycos Did you notice that the answer below was posted a few minutes before mine, yet was not the accepted answer? There was a reason. Sometimes the shortest answer is not the correct one for the question because it could be a homework and the teacher wants the students to learn the basics, like loops and conditions. Your comment about globals and var is too general. We know when to use them and when not. Again, the answer was based on the question, so understand before you comment. It's not a generic answer or a guide on how to code. There is a detailed explanation to learn from.

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.