0

I have an array ["a", "b", "c", "d", "e", "f"] and also an subarray ["a", "b", "c"] . Now the next element in the main array to subarray is d . So I want to get the array as ["a", "b", "c", "d"] .

I know there are so many ways to get this . Like

get length of subarray => 3
slice from main array `length of subarray + 1` => _.slice(main_array, 0, 4)

Is there any other elegant way to do this , I am preferably looking for solution using lodash.

Dibshare
  • 95
  • 2
  • 13
  • 1
    If you know for a fact that `subarray` starts at the start of the array (i.e. it’s a prefix), then I don’t think you’re going to get much simpler than the solution you described (which seems perfectly clean). You don’t need Lodash to slice, either: `main_array.slice(0, subarray.length + 1)` – Ry- Jul 08 '22 at 04:23
  • @Ry- yes `subarray` will be always a prefix. Thanks for the suggestion. – Dibshare Jul 08 '22 at 04:28
  • `slice` (Lodash or plain JS) is pretty elegant. Lodash offers `take` which basically just saves you passing the zero: `_.take(main_array, subarray.length + 1)`. But I wouldn't use Lodash *just* for that. If you already have Lodash for other stuff in your project, then go ahead and use it but don't add it just for this task. – VLAZ Jul 08 '22 at 04:59
  • @VLAZ yes we are using `lodash` extensively . – Dibshare Jul 08 '22 at 06:08
  • My dude @VLAZ closed the question minutes before I could answer with a use of the **spread operator**: `[...subarray, main_array[subarray.length]]` No function calls, no number operations. – Luciano Ferraz Jul 08 '22 at 11:25

0 Answers0