Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove specific elements from array in javascript

I am having a array called valueArray. I need to remove values which are ending with "/". Like I need to remove my-app/ , my-app/public/, my-app/src/.

const valueArray = [
  'my-app/',
  'my-app/.env',
  'my-app/.gitignore',
  'my-app/package-lock.json',     
  'my-app/package.json',
  'my-app/public/',
  'my-app/public/manifest.json',  
  'my-app/public/robots.txt',     
  'my-app/README.md',
  'my-app/src/',
  'my-app/src/App.css',
  'my-app/src/App.js',
  'my-app/src/App.test.js',       
  'my-app/src/index.css',
  'my-app/src/index.js',
  'my-app/src/reportWebVitals.js',
  'my-app/src/setupTests.js'      
]

for (let index = 0; index < valueArray.length; index++) {
        if(valueArray[index].charAt(valueArray[index].length-1) === "/"){
          valueArray.splice(valueArray[index],1);
        }
      }
console.log(valueArray);

I tried using splice and followed the syntax but it is not working. I am missing something. Can someone help with this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are using splice inside of a loop which iterates over the same array. To make sure you don’t skip over some indices you will have to add a index-- if you decide to splice.

You can also use the filter method of array to filter out items that don’t end with / which will be simpler in this scenario.

valueArray = valueArray.filter(item => item[item.length - 1] !== '/');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading