Home > front end >  How do I loop through an array in javascript to get a new array whose length is not greater than 4?
How do I loop through an array in javascript to get a new array whose length is not greater than 4?

Time:09-21

I have this array whose length could be any number but not less than 4. How do I loop through this array to get a new array that has a length not greater than 4? I tried using the filter method but it returned an empty array.

This is my attempt:

// array could be of any length but not less than 4.
const projects = [
  'landing page',
  'portfolio page',
  'e-commerce app',
  'Dapps',
  'signup page',
  // ... even more
];

const newProjects = projects.filter((project, index, array) => {
  return project[index <= 4]
})

console.log(newProjects);

CodePudding user response:

Corrected your approach;

const projects = ['landing page', 'portfolio page', 'e-commerce app', 'Dapps', 'signup page',.....] // array could be of any length but not less than 4

const newProjects = projects.filter((project, index, array) => {
  return index < 4;
})

console.log(newProjects);

Keep in mind that Array has zero-based index.

Proposed solution:

const newProjects = projects.slice(0,3);

CodePudding user response:

You can simply use slice() for this:

const projects = ['landing page', 'portfolio page', 'e-commerce app', 'Dapps', 'signup page'];

console.log(projects.slice(0,4));

Slice returns a portion of an existing array without modifying it.

  • Related