-1

I have a spreadsheet that has item/stock sent to me in the form of a single line such as:

item1,Add to Cart,item2,Out of Stock,...

I need to create an array of objects so that it looks like:

[["item1","Add to Cart"],["item2","Out of Stock"]]

From there, I intend to search the array for objects that match "Out of Stock"

I understand I can split on the comma, but how do I split and loop so that index 0,1 are created as an object and first item in a new array, so on and so forth?

Blogger11
  • 55
  • 1
  • 2
  • 11
  • 1
    `'item1,Add to Cart,item2,Out of Stock'.split(',').reduce((acc, item, i, arr) => (i%2) ? acc : [...acc, [item, arr[i+1]]], [])` – epascarello Jan 09 '23 at 18:51

1 Answers1

1

You could split, then reduce, where in your reduce if the index is odd you skip, and if it's not, you get the slice of hte current element and the next one.

console.log(
    'item1,Add to Cart,item2,Out of Stock'
        .split(',')
        .reduce((carry, _, i, arr) =>
            (i % 2)
            ? carry
            : [...carry, arr.slice(i, i + 2)]
        , [])
)
dave
  • 62,300
  • 5
  • 72
  • 93