-2

How to push all response' ids except first id ? I mean below code pushes all ids to idList array. I want to push all ids again but except first id should not be pushed.How to edit below code ?

const getAllId = async () => {
  let res = await axios({
    method: "get",
    url: "/v1/feed",
  });
  const idList = [];
  res.feed.forEach((item) => {
    idList.push(item.id);
  });
  return idList;
};
AKX
  • 152,115
  • 15
  • 115
  • 172
YusufOzt
  • 27
  • 8
  • er... use a counter? – Chris G Mar 23 '23 at 11:46
  • Does this answer your question? [How to skip first in map function](https://stackoverflow.com/questions/40679613/how-to-skip-first-in-map-function) – pilchard Mar 23 '23 at 11:54
  • combined with [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – pilchard Mar 23 '23 at 11:56

2 Answers2

1

Use .map to transform an array to an array, and .slice() to skip the first item in res.feed.

const res = await axios({
  method: "get",
  url: "/v1/feed",
});
return res.feed.slice(1).map(item => item.id);

If you really want to use forEach and not slice the feed, use the index parameter it passes to the callback:

const idList = [];
res.feed.forEach((item, index) => {
  if(index > 0) idList.push(item.id);
});
return idList;
AKX
  • 152,115
  • 15
  • 115
  • 172
0

Try This One Example

const ids = [1, 2, 3, 4, 5];
const newIds = ids.slice(1); // get a copy of the array from the second element to the end
console.log(newIds); // Output: [2, 3, 4, 5]
Talha Abid
  • 11
  • 2