How to change index of an element in an array (list) in aura component - Salesforce Globe For You
ChangeIndexOfAnElement.cmp
<aura:component >
<aura:attribute name="fruits" type="List" default="['Mango','Apple','Orange','Kiwi']"/>
<aura:attribute name="oldIndex" type="Integer"/>
<aura:attribute name="newIndex" type="Integer"/>
The available fruits are <br/>
<aura:iteration items="{!v.fruits}" var="fruit" indexVar="index">
{!index}) {!fruit}<br/>
</aura:iteration>
<br/>
<lightning:input type="number" name="beforeIndex" label="Enter current Index" value="{!v.oldIndex}"/>
<lightning:input type="number" name="after Index" label="Enter new Index" value="{!v.newIndex}"/>
<br/><lightning:button variant="brand" label="Change Index" title="Brand action" onclick="{!c.changeIndex}" />
</aura:component>
ChangeIndexOfAnElementController.js
({
changeIndex : function(component, event, helper) {
var oldIndex =component.get("v.oldIndex");
var newIndex = component.get("v.newIndex");
var fruits = component.get("v.fruits");
if(newIndex >=fruits.length){
var temp = newIndex - fruits.length+1;
while(temp--){
fruits.push(undefined);
}
}
fruits.splice(newIndex,0,fruits.splice(oldIndex,1)[0]);
component.set("v.fruits",fruits);
}
})
TestApp.app
<aura:application extends="force:slds">
<c:ChangeIndexOfAnElement/>
</aura:application>
Output: