简体   繁体   中英

Javascript: How to insert a hole into a sparse array or creating a hole

I'm using sparse arrays to be memory efficient with huge datasets. (and to signal the difference between a hole and a undefined or null entry) adding holes at the end is fine by setting datapoints.lentgh .

datapoints = [10,,,20,,,10,1]

No I face the problem how to insert a hole (say before 20)

datapoint.splice(3,0)

does not work, and I can't find a (easy) method to insert holes. (Think I have to rebuild the array but thought to ask before) Or is there a way to change a "defined" entry into a hole? delete datapoint[4]; creates an undefined entry not a hole:(

Your sparse array is actually an object. You can delete items and you can add items.

Let's suppose you want to add k holes before position offset . Then:

 datapoints = [10,,,20,,,10,1]; function addHoles(offset, k, datapoints) { let migration = {}; for (let key in datapoints) { let intKey = parseInt(key); if (intKey >= offset) { migration[intKey] = datapoints[intKey]; delete datapoints[intKey]; } } for (let key in migration) { let intKey = parseInt(key); datapoints[intKey + k] = migration[intKey]; } return datapoints; } console.log(addHoles(3, 3, datapoints));

Think I could work with

datapoint.splice(3,0,undefined);
delete datapoint[3]

It looks like that I have a hole now....

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