Easiest way here would be to concat new element to an array. In case condition is true, you will concat new element. Consider this examples:
// using if statement
const type = "typeA";
let additionalCardOfTypeA = {
name: "Card A",
size: "Medium",
action: "make",
};
let typesOfCards = [
{ name: "Card A", size: "Medium", action: "make" },
{ name: "Card B", size: "Small", action: "break" },
{ name: "Card C", size: "Large", action: "build" },
];
if (type === "typeA") {
typesOfCards = typesOfCards.concat(additionalCardOfTypeA);
}
// using ternary operator
const type = "typeA";
let additionalCardOfTypeA = {
name: "Card A",
size: "Medium",
action: "make",
};
let typesOfCards = [
{ name: "Card A", size: "Medium", action: "make" },
{ name: "Card B", size: "Small", action: "break" },
{ name: "Card C", size: "Large", action: "build" },
].concat(
type === "typeA"
? additionalCardOfTypeA
: []
);
Edit
To insert new element in particular place you will have to create additional arrays. First, find a place for your element. Then, create an array that have everything before said index in original, and array that have everything from index to an end. Then concatenate start, new element and end into final array.
const type = "typeA";
let additionalCardOfTypeA = {
name: "Card A",
size: "Medium",
action: "make",
};
let typesOfCards = [
{ name: "Card A", size: "Medium", action: "make" },
{ name: "Card B", size: "Small", action: "break" },
{ name: "Card C", size: "Large", action: "build" },
];
if (type === "typeA") {
let indexForNewElement = getSomehowIndex();
// Getting everything before index
let head = typesOfCards.slice(0, indexForNewElement);
// Getting everything after index
let tail = typesOfCards.slice(indexForNewElement);
typesOfCards = head.concat(additionalCardOfTypeA).concat(tail);
}
mapitnullorundefinedvalues inside the array. remove them or just don't add themtypesOfCardsdo the conditional part.