1

I am trying to convert:

var ic = [[[123,231,12],[56,43,124]],[[78,152,76],[64,132,200]]]

to (each element of the sub array has the average value of the sub array)

var ig = [[[122,122,122],[74,74,74]],[[102,102,102],[132,132,132]]]

Here is my code, the average function works, but it is not returning the correct new array:

var color2grey = function (image /* this is the image in color*/) {

const average = function([a,b,c]) {
return [((a+b+c)/3), ((a+b+c)/3), ((a+b+c)/3)]
};

return image.map(function(subArray) {
 average(subArray);
});

}

This is what I am getting:

returns- (2) [undefined, undefined] 0 : undefined 1 : undefined length : 2 proto : Array(0)
2
  • You could try adding the output you are getting, what the function returns so it helps in debugging. Commented May 16, 2017 at 13:04
  • returns- (2) [undefined, undefined] 0 : undefined 1 : undefined length : 2 proto : Array(0) Commented May 16, 2017 at 13:06

2 Answers 2

1

You can use map() method to make new array and inside you can use reduce() to calculate average of each array and Array.fill() to add avg values to new array.

var ic = [[[123,231,12],[56,43,124]],[[78,152,76],[64,132,200]]] 

var result = ic.map(a => a.map(function(e) {
  var avg = e.reduce((r, e) => r + e) / e.length
  return Array(e.length).fill(parseInt(avg))
}))

console.log(result)

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

Comments

0

You could map the outer arrays, get the average of the most inner array and map for each item the average value.

var ic = [[[123, 231, 12], [56, 43, 124]], [[78, 152, 76], [64, 132, 200]]],
    ig = ic.map(function (a) {
        return a.map(function (b) {
            var avg = Math.floor(b.reduce(function (a, b) { return a + b; }) / b.length);
            return b.map(function () { return avg; });
        });
    });

console.log(ig);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6

var avg = array => array.reduce((a, b) => a + b) / array.length,
    ic = [[[123, 231, 12], [56, 43, 124]], [[78, 152, 76], [64, 132, 200]]],
    ig = ic.map(a => a.map(b => Array(b.length).fill(Math.floor(avg(b)))));

console.log(ig);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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.