2016-07-14 95 views
1

我有一個數組,我需要大塊數組&操縱塊的部分,但我想它來更新我的原數組過濾器對象引用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>

+0

你只要改變在'markers'('標記[4] = 「NEWVALUE」')第五元件?或者每五分之一? – Andreas

+0

只有一個項目。但是,是否可以通過塊[0] [4]更新標記[4],並將標記[4]自動更新爲塊[0] [4]的新值? –

+0

如果你只想改變第五個元素,那麼絕對不需要'_.chunk \ chunks' – Andreas

回答

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);