1

i want to push à value in array , but not at the end, not at the start, at the first empty index

Show the code exemple:

var test=new Array();
test[0]="Lionel";
test[2]="Jhon";
test.push("Cloé");

result:

[ 'Lionel', <1 empty item>, 'Jhon', 'Cloé' ]

And i need to have Cloé just after Lionel Thanks

Edit this is different to insert in specific index, because i can't know the number of empty index, this is slot system . And i just wanna know if we have native solution ?.

5
  • test[1] = 'Cloe'? Commented Sep 8, 2017 at 12:18
  • 3
    push simply does test[test.length] = value. If you have a different definition of what it should do you need to implement it yourself with a loop. Commented Sep 8, 2017 at 12:19
  • Check this out stackoverflow.com/questions/586182/… Commented Sep 8, 2017 at 12:21
  • Possible duplicate of How to insert an item into an array at a specific index? Commented Sep 8, 2017 at 12:21
  • is the unset index undefined, null or <1 empty item>? Commented Sep 8, 2017 at 12:21

6 Answers 6

2

You could search for a sparse index and return this index for inserting a value.

function getIndex(array) {
    var last = 0;
    array.some(function (_, i) {
        return last < i || !++last;
    });
    return last;
}

var test = ["Lionel", , "Jhon"];

test[getIndex(test)] = "Cloé";

console.log(test);

Sign up to request clarification or add additional context in comments.

Comments

1

You could write a simple function to look for a gap with undefined as the value and place the new value if if found - otherwise just push to the end of the array

function insertFirstGap(array, value){
    for(var i = 0;i<array.length;i++){
        if(array[i] === undefined){
            array[i] = value; 
            return; 
        }
    }
    array.push(value);

}

Live example below:

var test=new Array();
test[0]="Lionel";
test[2]="Jhon";

insertFirstGap(test,"Cloé");

console.log(test, test.length);

function insertFirstGap(array, value){
    for(var i = 0;i<array.length;i++){
        if(array[i] === undefined){
            array[i] = value;  
            return;
        }
    }
    array.push(value);
     
}

5 Comments

Hello, this is the same code i write, but i search a native function , thanks you have understand my problem, and your solution is correct, now i know we don't have native solution !
if you have a value of undefined, i gets overwritten.
@NinaScholz I thought that was the requirement. If its not ive misunderstood.
maybe we define "empty" different. for me, an empty element is only possible to check with in operator (--> false) or with an iteration with a method, where the sparse items are not visited.
@NinaScholz yeah you have a valid point. I suspect undefined will probably satisfy this person's requirement. But you are fo course logically correct.
0

you can do it in the following way

var test=new Array();
test[0]="Lionel";
test[2]="Jhon";

let x = test.length;
Object.keys(test).forEach(function(element, idx){
    if(element != idx){
        x = (x==test.length ? idx: x);
    }
})
test[x] = "Cloe"
console.log(test);

Comments

0

Solution 1

If you know which index you want to apply the value to, use test[x] = "Cloe".

Solution 2

If you want to apply the value to the first empty item, use a for loop that goes through every item in the array until it finds one that's empty.

test = ["Lionel", "", "Jhon", ""];

for (var i = 0; i < test.length; i++) {
  if (!test[i]) {
    test[i] = "Cloe";
    break;
  }
}

console.log(test)

EDIT:

If you only want to use native functions. Use splice and indexOf.

test = ["Lionel", "", "Jhon", ""];

test.splice(test.indexOf(""), 1, "Cloe")

console.log(test)

test.splice(index, 1, item) inserts item into test at the specified index. indexOf("") search for an array with no value in it and return its position.

7 Comments

i don't know the index, and i search if we have native solution.
@LionelR If you don't know the index, then try Solution 2. Also, what do you mean by "native solution"?
Native solution is function include in es6 . push is native for exemple , this is not a function you must write.
@LionelR Then you can use the splice function, test.splice(test.indexOf(""), 0, item), to insert item into test at the index where "" is located.
if i have "" entry on my array ?
|
0

Ok, we don't have native solution, this is my solution with code, my final objective is slot systeme :

 FindValidSocket(Type){
    let count=0;
    while (count!==this.Max[Type]){
        if(typeof(this.traitement[Type][count])==="undefined"){
            return count;
        }else{
            count++;
        }
    }
    return false;
}

Thanks all for your response

Comments

-1
function insertIntoFirstEmpty(val, arr) {
   for(var i = 0;i<arr.length;i++) {
      if(typeof arr[i] === 'undefined')
      {
         arr[i] = val;
         return;
      }
   }
   arr.push(val);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.