Home > Net >  How to remove elements of array in order of index range?
How to remove elements of array in order of index range?

Time:10-30

I have an array:

const savings = [" 10$", "-22.50$", " 5$", " 22.40$", "-3.5$"]; 

I want to show elements only in a certain range of array indexes. For example: how to show everything between array index 1 (-22.50$) and array index 3 ( 22.50$)? All elements with lower or higher indexes should be removed.

CodePudding user response:

There are many ways to do so:

slice (returns new array)

savings.slice(1,4) // ['-22.50$', ' 5$', ' 22.40$']

splice (modifies array)

savings.splice(1,3) // ['-22.50$', ' 5$', ' 22.40$']


...plus many other more complicated techniques including but not limited to:

filter (returns new array)

in this case it's effectively just a .slice.

// ['-22.50$', ' 5$', ' 22.40$']
savings.filter((price, index) => index >= 1 && index <= 4)

CodePudding user response:

You can use the filter method of an array.
Here is the code snippet.
The newArray will hold the value you required.

const savings = [" 10$", "-22.50$", " 5$", " 22.40$", "-3.5$"];
const newArray = savings.filter((value, index, array) => {
    num = parseFloat(value.slice(0, value.length - 1)); // convert string into number to compare.
    min = parseFloat(array[1].slice(0, array[1].length - 1)); // convert string into number to compare.
    max = parseFloat(array[3].slice(0, array[3].length - 1)); // convert string into number to compare.

    if (value < min || value > max) { // check required condition
        return false;
    }

    return true;
});

  • Related