I have two array
const array1 = [12, 13, 14, 15, 16, 17, 18, 19, 20]
const array2 = [17, 18]
I want to return first three element from array1 after comparing the index of array2 17 element or first element with the array1.
desired O/P from array1 after comparing is [14, 15, 16]
i have tried getting the index of the particular element.
const indexOf17FromArray1 = array1.indexOf(array2[0]) //5
just do array.slice((idx - 3), idx)
You can combine the use of array methods indexOf and slice.
First determine the last index (like you already have). Then based on your desired length modify it for use with slice. slice takes the start and end indices.
const array1 = [12, 13, 14, 15, 16, 17, 18, 19, 20];
const array2 = [17, 18];
const length = 3;
const indexOf17FromArray1 = array1.indexOf(array2[0])
console.log(array1.slice(indexOf17FromArray1 - length, indexOf17FromArray1));
You could get the index and check if -1 or subtract an offset and get a new array.
const
array = [12, 13, 14, 15, 16, 17, 18, 19, 20],
value = 17,
index = array.indexOf(value),
result = index === -1
? []
: array.slice(Math.max(index - 3, 0), index);
console.log(result);