Reputation: 1077
I have a somewhat complicated task of slicing and dicing an array of data into a sensible JSON Object. The first step is to slice the array into smaller arrays based on the content of the elements.
In this simplified version I want to break one big array into a series of smaller arrays defined by the word "that."
Given this array:
that, thing, thing, that, thing, that, thing, thing, thing
I want to return:
[that, thing, thing],
[that, thing],
[that, thing, thing, thing],
Upvotes: 2
Views: 112
Reputation: 86
You can use lastIndexOf, slice and unshift.
function test (a, b, item) {
var i = a.lastIndexOf(item);
while (i != -1) {
b.unshift(a.slice(i));
a = a.slice(0, i);
i = a.lastIndexOf(item);
}
return b;
}
var arr1 = [1, 2, 3, 1, 2, 1, 2, 3, 4];
var arr2 = [];
test(arr1, arr2, 1);
console.log(arr2);
Using nodejs to run the result is:
[ [ 1, 2, 3 ], [ 1, 2 ], [ 1, 2, 3, 4 ] ]
Upvotes: 0
Reputation: 45135
A quick reduce
should fix it:
var src = ["that", "thing", "thing", "that", "thing", "that", "thing", "thing", "thing"]
var dest = src.reduce(function(p,d) {
if (d === "that") {
p.push([d]);
} else {
p[p.length-1].push(d);
}
return p;
},[]);
$("#json").text(JSON.stringify(dest));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="json"></div>
Upvotes: 0
Reputation: 6090
this is easy to do with Array.reduce()
:
var array = ["that", "thing", "thing", "that", "thing", "that", "thing", "thing", "thing"];
console.log(array.reduce(function(prev, cur, idx, arr) {
if (cur === "that") {
// start a new sub-array
prev.push(["that"]);
}
else {
// append this token onto the current sub-array
prev[prev.length - 1].push(cur);
}
return (prev);
}, []));
Upvotes: 1
Reputation: 9836
This is going to be manual work. I recommend a combination of indexOf (to find the "that") and splice (to remove the relevant sub-array).
var input = ["that", "thing", "thing", "that", "thing", "that", "thing", "thing", "thing"];
var output = [];
for (var idx = input.indexOf("that", 1); idx !== -1; idx = input.indexOf("that", 1)) {
output.push(input.splice(0, idx));
}
output.push(input);
Upvotes: 0
Reputation: 1788
var arr = ['that', 'thing', 'thing', 'that', 'thing', 'that', 'thing', 'thing', 'thing'];
var subArrays = [];
var subArrayItem = [];
arr.forEach(function(arrItem) {
if(arrItem == 'that') {
if(subArrayItem.length) // avoid pushing empty arrays
subArrays.push(subArrayItem)
subArrayItem = []
}
subArrayItem.push(arrItem)
})
if(subArrayItem.length) // dont forget the last array
subArrays.push(subArrayItem)
Upvotes: 1