2017-09-28 19 views
5

Jak mogę porastać tablicę według elementu?Tablica fragmentów według elementu

Na przykład lodash ma funkcję wyrwy tablic o długości

_.chunk(['a', 'b', 'c', 'd'], 2); 
// => [['a', 'b'], ['c', 'd']] 

_.chunk(['a', 'b', 'c', 'd'], 3); 
// => [['a', 'b', 'c'], ['d']] 

więc mieć tablicę jak poniżej: [ „a”, „b”, „*”, „c”] można coś podobnego

chunk(['a', 'b', '*', 'c'], '*') 

który da mi

[['a', 'b'], ['c']] 

jest coś takiego rozłamu strun na tablicy

+1

Próbowałeś kilka rzeczy? Możesz uzyskać indeks używając 'Array.indexOf ('*')' w oparciu o niego utworzy podplanery – Satpal

+0

znajdź indeks ''*'', a następnie przekaż ten indeks do ['Array.slice'] (https: // developer. mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). –

+0

result = array.join (""). Split ("*"). Map (function (d) {return d.split ("")}) – krishnar

Odpowiedz

4

Można użyć array.Reduce:

var arr = ['a', 'b', '*', 'c']; 
 
var c = '*'; 
 
function chunk(arr, c) { 
 
    return arr.reduce((m, o) => { 
 
     if (o === c) { 
 
      m.push([]); 
 
     } else { 
 
      m[m.length - 1].push(o); 
 
     } 
 
     return m; 
 
    }, [[]]); 
 
} 
 
console.log(chunk(arr, c));

+0

Poprawiona wersja: https://jsfiddle.net/e75ofhL9/ – dfsq

1

Stosując tradycyjne pętle:

function chunk(inputArray, el){ 
 

 
    let result = []; 
 
    let intermediateArr = []; 
 

 
    for(let i=0; i<inputArray.length; i++){ 
 

 
     if(inputArray[i] == el) 
 
     { 
 
     result.push(intermediateArr); 
 
     intermediateArr=[]; 
 
    
 
     }else { 
 
     intermediateArr.push(inputArray[i]); 
 
     } 
 
    
 
    } 
 

 
    if(intermediateArr.length>0) { 
 
     result.push(intermediateArr); 
 
    } 
 

 
    return result; 
 
     
 
} 
 

 
console.log(
 
    chunk(['a', 'b', '*', 'c', 'd', 'e', '*', 'f'], '*') 
 
)

0

Trochę rekurencji.

function chunk (arr, el) { 
 
    const index = arr.indexOf(el); 
 
    var firstPart; 
 
    var secondPart; 
 
    if(index > -1) { 
 
    \t \t firstPart = arr.slice(0, index); 
 
     secondPart = arr.slice(index + 1); 
 
    } 
 
    if(secondPart.indexOf(el) > -1) { 
 
    \t return [firstPart].concat(chunk(secondPart, el)); 
 
    } 
 
    return [firstPart, secondPart]; 
 
} 
 

 
console.log(
 
    chunk(['a', 'b', '*', 'c', 'd', 'e', '*', 'f'], '*') 
 
)

Powiązane problemy