Javascript (dynamic) insert into array, then shift all elements underneath +1
arrays, html, javascript
Solution
If you know the position you want to insert the element into:
Use the splice method. It's cheap and works exactly like you want. You can also insert multiple elements at once:
var strings = ["14S", "16S", "19S"];
strings.splice(1,0,"15S");
Result
"14S" "15S" "16S" "19S"
You should also use this solution if you don't want the array to be sorted in a specific way.
If you don't know the position you want to insert the element into:
You will have to resort to a push/sort combination, supplying your own sort algorithm (unless the standard sort is enough)
var strings = ["14S", "16S", "19S"];
strings.push("15S");
strings.sort(function(a, b){
if (a is less than b by some ordering criterion)
return -1;
if (a is greater than b by the ordering criterion)
return 1;
// a must be equal to b
return 0;
});
Problem
Didn't really found a solution to this for Javascript. What I need; I want to insert an element into an array, but not really overwrite that element. Rather a 'dynamic' insert. Thus Insert element, then shift all elements underneath it by +1 index. For instance: ``` I have an array "14S" "16S" "19S". I know want to insert "15S". The resulting array: "14S" "15S" "16S" "19S" ``` What i tried: ``` fullName = "15S" low = 5; cardsS[low] = fullName; for (var i = low; i < cardsS.length; i++) { cardsS[i + 1] = cardsS[i]; } ```