Home > OS >  How to get three element after an particular index of a array?
How to get three element after an particular index of a array?

Time:03-23

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

CodePudding user response:

Here is a very simple function that will give you the next three after

your supplied index.

const array = [1,2,3,4,5,6,7,8,9];
const index = 2;
const threeElementsAfterIndex = [];
for( let i = 0; i < array.length; i   ) {
    if(i > index && i < index   3) {
        threeElementsAfterIndex.push(array[i]);
    }
}
return threeElementsAfterIndex;

CodePudding user response:

const array = [1, 2, 3, 4, 5, 6, 7, 8];
const index = 2;


console.log(array.slice(index   1, index   4));

CodePudding user response:

just do array.slice((idx - 3), idx)

CodePudding user response:

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));

CodePudding user response:

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);

CodePudding user response:

Get the index of the element you want as reference.

const index = array1.indexOf(array2[0]);

If you want 3 elements after this index:

array1.slice(index   1, index   4);

If you want 3 elements before this index:

array1.slice(index - 3, index);

CodePudding user response:

Finding the index of element = 17 in array1:

const array1 = [12, 13, 14, 15, 16, 17, 18, 19, 20];
const array2 = [17, 18];

const position17 = array1.findIndex(e => e === array2[0]);

The method findIndex will loop through array1 and check if the current element(e) is equal to array2[0].

Creating an array only with the three elements prior to element 17:

Here you will use the filter method, I'm passing the current value(item) and it's index. This method will check if the index is below "positon17" and if it is whitin the first three elements prior to element 17.

const newArray = array1.filter((item, index)=> (index < position17 & index >=position17-3)&& item);
console.log(newArray);
  • Related