如果給定一個元素陣列let array = ['apple', 'banana', 'salami', 'cheese']
獲得此結果的最佳做法是什么:['applebanaa' , 'salamicheese']
我的第一個想法是使用 reduce ,它可以作業,但它將每個字串連接成一個長字串。 請參閱下面的示例
```let array = ['apple', 'banana', 'salami', 'cheese']"
array.reduce((a,b) => a b);
output : applebanaasalamicheese```
我覺得我在這里走在正確的軌道上。也許我需要對 reduce 括號內的方程做一些事情以獲得我正在尋找的結果?
我對 Javascript 比較陌生,但我希望這個問題足夠清楚,可以理解。提前感謝您的幫助!
此致
uj5u.com熱心網友回復:
reduce這里會顯得非常笨拙。輸出結構是一個字串陣列,與輸入不是一對一的,所需的輸出不是數字或原語。在回圈外創建變數并推送到它比每次回傳相同的累加器陣列更容易。
for一次迭代索引的普通回圈i將起作用i 1。
const array = ['apple', 'banana', 'salami', 'cheese'];
const output = [];
for (let i = 0; i < array.length; i = 2) {
output.push(array[i] (array[i 1] || ''));
}
console.log(output);
如果你真的想使用.reduce...
const array = ['apple', 'banana', 'salami', 'cheese'];
const output = array.reduce((a, str, i) => {
if (i % 2 === 0) {
a.push(str);
} else {
a[a.length - 1] = str;
}
return a;
}, []);
console.log(output);
uj5u.com熱心網友回復:
您可以將Array.prototype.reduce()與Array.prototype.concat( ) 結合使用
代碼:
const array = ['apple', 'banana', 'salami', 'cheese']
const result = array.reduce((a, c, i, arr) =>
a.concat(i % 2 === 0 ? [c (arr[i 1] || '')] : []), [])
console.log(result)
您也可以將Array.prototype.filter()與Array.prototype.map( ) 結合使用
代碼:
const array = ['apple', 'banana', 'salami', 'cheese']
const result = array
.filter((_, index) => index % 2 === 0)
.map((item, index) => item (array[index * 2 1] || ''))
console.log(result)
uj5u.com熱心網友回復:
如果你只想加入字串,你可以使用 array.join()
const sampleArray = ['apple', 'banana', 'salami', 'cheese']
const joinedArray = SampleArray.join(' ') // "apple banana salmi cheese"
您可以選擇空格 (' ') 或逗號作為分隔符,請參閱此處的檔案 Array.join()
uj5u.com熱心網友回復:
您正在尋找的模式似乎可以chunk(2)在map(join('')) chunk其他庫中的 lodash 中使用,或者您可以自己實作它。
// If given an array of elements let array = ['apple', 'banana', 'salami', 'cheese']
// What is the best practice to get this result : ['applebanaa' , 'salamicheese']
const array = ['apple', 'banana', 'salami', 'cheese'];
// https://lodash.com/docs/4.17.15#chunk
// https://stackoverflow.com/questions/8495687/split-array-into-chunks
function chunk(array, size = 1) {
let chunked = [];
for (let i = 0; i < array.length; i =size) {
chunked.push(array.slice(i, i size));
}
return chunked;
}
/* Chunk will divide up the array in to size batches
* and return an array of arrays of elements of the
* chunk size.
*/
// const chunked = chunk(array, 2);
// chunked = [['apple', 'banana'], ['salami', 'cheese']];
// Here is the final expression
console.log(
chunk(array, 2)
.map(chunk => chunk.join(''))
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493167.html
標籤:javascript 数组 减少
下一篇:如何計算哪個組中有多少專案?
