使用对象引用过滤lodash

时间:2016-07-14 14:36:50

标签: javascript lodash

我有一个数组,我需要将那个数组和数组分块。操纵块的部分但是我想更新我的原始数组

我是自学成才,没有计算机科学背景,所以当涉及技术内部工作时,我处于劣势。

var markers = ["one","two","three","four","five","six","seven","eight","nine"]

var chunks = _.chunk(markers, 5)
var result = _.chain(chunks[0]).last().value();

result = 'newValue'
console.log(chunks);

console.log(markers);
//was hopping to get
// ["one","two","three","four","newValue","six","seven","eight","nine"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

1 个答案:

答案 0 :(得分:0)

我不太确定我的要求是否合适,但这会改变每个“块”的第一个和最后一个元素(没有真正拆分数组)。

var data = [
    "one","two","three","four","five",
    "one","two","three","four","five",
    "one","two","three"
];

var chunkSize = 5,
    numberOfChunks = Math.ceil(data.length / chunkSize),
    indexOfFirstElementInChunk,
    indexOfLastElementInChunk;

for (var i = 0; i < numberOfChunks; i++) {
    indexOfFirstElementInChunk = (i * chunkSize);
    data[indexOfFirstElementInChunk] = "first element";
  
    indexOfLastElementInChunk = Math.min(data.length, ((i + 1) * chunkSize)) - 1;
    if (indexOfFirstElementInChunk < indexOfLastElementInChunk) {
      data[indexOfLastElementInChunk] = "last element";
    }
}

console.log(data);