-2

If I have a certain sequential number of items within an array (say from index 0 - 31) that I want to push to a new array, how can I do that? Basically I want some logic that says, take items with an index of 0 - 31, and push them to a new array.

I know how to get the index when I know the string value, such as this:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let a = fruits.indexOf("Apple"); // will be 2

.., but how do I push to a new array a subset of indexed items, like from 0 - 31, as I mentioned.

Rey
  • 1,193
  • 1
  • 11
  • 20
  • what is desired output ? – Code Maniac Sep 15 '19 at 02:37
  • A new array with the contents of all the items of the original array that had an index from 0 - 31 -- so the first 31 items in the original array. – Rey Sep 15 '19 at 02:38
  • Are you looking to splice? `var months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); // inserts at index 1` – Get Off My Lawn Sep 15 '19 at 02:38
  • @Ademo so you want to copy the array? – Nick Parsons Sep 15 '19 at 02:41
  • I want a copy of the subset of the array. It's been pointed out that I can do this with `slice()`, since that allows me to specify the beginning and ending index to include -- which is exactly what I need. – Rey Sep 15 '19 at 02:44
  • Possible duplicate of [How to merge two arrays in JavaScript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Rey Sep 15 '19 at 02:48

2 Answers2

2

Have you tried using slice? It will return a shallow copy of a portion of an array into a new array object selected from the start to end index.

For example:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.slice(1, 3)) // logs: ["Orange", "Apple"]
skovy
  • 4,535
  • 2
  • 14
  • 31
  • Ah, right. Yes, of course, with slice() we can specify the beginning and ending indexes. Thanks, @skovy! – Rey Sep 15 '19 at 02:42
1

You could use a filter to select the range of items that you want, where the second parameter is the index.

const fruits = ["Banana", "Orange", "Apple", "Mango"];

const getRange = (arr, start, end) => arr.filter((itm, idx) => idx >= start && idx <= end)

console.log(getRange(fruits, 2, 3))
console.log(getRange(fruits, 0, 2))
Get Off My Lawn
  • 27,770
  • 29
  • 134
  • 260