javascript - Slice into chunks and average (reduce) array in JS - Stack Overflow

I have an array:var data = [0,1,2,3,4,5];that I would like to splice into [0,1,2] and [3,4,5] followed

I have an array:

var data = [0,1,2,3,4,5];

that I would like to splice into [0,1,2] and [3,4,5] followed by averaging it so the final result would be:

var dataOptimised = [1,4];

this is what I have found so far:

function chunk (arr, len) {

    var chunks = [];
    var i = 0;
    var n = arr.length;

    while (i < n) {
      chunks.push(arr.slice(i, i += len)); // gives [[0,1,2] [3,4,5]]
    }

    return chunks;

};

How to reduce it?

Thanks

I have an array:

var data = [0,1,2,3,4,5];

that I would like to splice into [0,1,2] and [3,4,5] followed by averaging it so the final result would be:

var dataOptimised = [1,4];

this is what I have found so far:

function chunk (arr, len) {

    var chunks = [];
    var i = 0;
    var n = arr.length;

    while (i < n) {
      chunks.push(arr.slice(i, i += len)); // gives [[0,1,2] [3,4,5]]
    }

    return chunks;

};

How to reduce it?

Thanks

Share Improve this question asked May 3, 2018 at 14:55 lovemyjoblovemyjob 5791 gold badge5 silver badges22 bronze badges 1
  • Do you mean you want less code to acplish what you're doing? And are you asking for a solution that works dynamically based on the array's size? – homersimpson Commented May 3, 2018 at 14:57
Add a ment  | 

6 Answers 6

Reset to default 5

Sum each chunk using Array.reduce() and divide by the chunk's length.

var data = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30];

function chunkAverage(arr, len) {
    var chunks = [];
    var i = 0;
    var n = arr.length;
    
    var chunk;

    while (i < n) {
      chunk = arr.slice(i, i += len);
      chunks.push(
        chunk.reduce((s, n) => s + n) / chunk.length
      );
    }

    return chunks;
};

console.log(chunkAverage(data, 3));

You can map the array and reduce it.

function chunk(arr, len) {
  var chunks = [];
  var i = 0;
  var n = arr.length;

  while (i < n) {
    chunks.push(arr.slice(i, i += len)); // gives [[0,1,2] [3,4,5]]
  }

  return chunks;
};

var data = [0, 1, 2, 3, 4, 5];

var result = chunk(data, 3).map(o => (o.reduce((c, v) => c + v, 0)) / o.length);

console.log(result);

Split the array in half using splice. And use .reduce to take sum and average finally

var arrR = [0, 1, 2, 3, 4, 5],
    arrL = arrR.splice(0, Math.ceil(arrR.length / 2)),
    results = [getAverave(arrL), getAverave(arrR)];
console.log(results)

function getAverave(arr) {
    return arr.reduce(function(a, b) {
        return a + b;
    }) / arr.length;

}

Here is the sortest answer possible for this question. n is the index you want to slice from.

function chunk (arr, n) {
   return [Math.sum.apply(null, arr.slice(0, n)), Math.sum.apply(null, arr.slice(n, arr.length))];
};

If you don't mind using underscore.js, you can use the _.chunk() function to easily chunk your array, then map() each chunk to a reduce() function which averages each chunk.

When importing the underscore.js library, you can reference the library using the _ symbol.

const arr = [0, 1, 2, 3, 4, 5];
const len = 3;

const result = _.chunk(arr, len).map(chunk => chunk.reduce((a, b) => a + b, 0) / chunk.length);
console.log(result); // Outputs [1, 4]

If you have an odd-length array; say that arr = [0, 1, 2, 3, 4, 5, 6], then result would be [1, 4, 6].

In HTML, you can include the library in a <script> tag:

<script src="http://underscorejs/underscore.js"></script>

Here's a working jsfiddle where you can see it in action (you'll have to open the F12 tools to see console output; the StackOverflow embedded snippets are kind of funky and don't work right).

Agreeing with both Ori Drori and Eddie, but I thought I might also provide some additional minor changes to your chunk function for consistency and maintainability's sake...

When writing JavaScript, I would remend using function names that won't collide with mon/expected variable names. For example, with a function like chunk() that returns a "chunk", it's likely you would want to create a variable called chunk to hold its return value. A line of code like var chunk = chunk() is an obvious problem, but if it gets any less direct it can easily wreak havoc down the line. Using the const var = function pattern (see snippet) helps you avoid writing over the original function by throwing an error on the correct line, but I would argue it's also still good to get in the habit of using a naming convention that doesn't have this drawback just in case you can't use something like const. My approach is to always include a verb in the function name. In your case, "chunk" can also be considered a verb, but it conflicts. So, I prefixed it with "get".

const getChunk = (arr, len) => {
    const chunks = []
    const n = arr.length
    let i = 0

    while (i < n) {
      chunks.push(arr.slice(i, i += len))
    }

    return chunks
}

const data = [0,1,2,3,4,5]

const optimizedData =
  getChunk(data, 3).map(chunk =>
    chunk.reduce((total, val) => total + val) / chunk.length
)

console.log(optimizedData)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742307287a4419193.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信