简体   繁体   中英

How to remove elements of array in order of index range?

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.

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)

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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM