从数组中检索数量均匀分布的元素 [英] Retrieve an evenly distributed number of elements from an array

查看:150
本文介绍了从数组中检索数量均匀分布的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何提取数组中的第n个项目,但是我遇到的困难是:

I know how to extract every nth item in an array, but what I have difficulties with is the following:

如何从数组中提取第n个项目总共256个元素中的1800个元素(总包括第一个和最后一个元素)?

How can I extract every nth item from an array of 1800 elements, always including the first and the last element, up to a total of 256 elements?

示例:

array = [1,2,3,4,5,6,7,8,9,10];

提取5个元素:

extract = [1,3,5,7,10];


推荐答案

喜欢吗?

/**
 * Retrieve a fixed number of elements from an array, evenly distributed but
 * always including the first and last elements.
 *
 * @param   {Array} items - The array to operate on.
 * @param   {number} n - The number of elements to extract.
 * @returns {Array}
 */
function distributedCopy(items, n) {
    var elements = [items[0]];
    var totalItems = items.length - 2;
    var interval = Math.floor(totalItems/(n - 2));
    for (var i = 1; i < n - 1; i++) {
        elements.push(items[i * interval]);
    }
    elements.push(items[items.length - 1]);
    return elements;
}

示例:

// Set up an array for testing purposes
var items = [];
for (var i=1; i<= 1800; i++) {
    items.push(i);
}

var extracted = distributedCopy(items, 256);

console.log(extracted);

这篇关于从数组中检索数量均匀分布的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆