Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

81
Views
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 :(

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

Think I could work with

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

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!