Mr B
Mr B

Reputation: 4130

How to insert an element in a array of ReactJS component objects (between existing elements)

I have an array of <FilterGroup /> objects. I want to insert a <Conjunction />object after each <FilterGroup> object except the last one.

So the array should go from:

[
    <FilterGroup />
    <FilterGroup />
    <FilterGroup />
    <FilterGroup />
]

To:

[
    <FilterGroup />
    <Conjunction />  
    <FilterGroup />
    <Conjunction />
    <FilterGroup />
    <Conjunction />
    <FilterGroup />
]

My attempts so far have led me to:

filterGroups.filter(function(filterGroup, index) {
    if(index !== filterGroups.length-1){
        filterGroups.push(<Conjunction key={index} />);
    }
})

I need to replace push() as it appends the element onto the end of the array.

Upvotes: 0

Views: 320

Answers (2)

Richard Roncancio
Richard Roncancio

Reputation: 61

You can perform a reduce operation to include the Conjunction component after the FilterGroup component:

filterGroups.reduce(function (acc, element, index, array){
    if(idx < array.length - 1) {
        return acc.concat([element, <Conjunction key={index + 1} />]);
    } else {
        return acc.concat([element])
    }
}, []);

But I must admit that this looks a bit weird, maybe you want to do that when you are iterating on the data array when creating the filterGroups array.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074088

The usual React-like way would be to create a new array:

const result = [];
for (const entry of original) {
    if (result.length > 0) {
        result.push("<Conjunction />");
    }
    result.push(entry);
}

Example using strings instead of elements:

var original = [
    "<FilterGroup />",
    "<FilterGroup />",
    "<FilterGroup />",
    "<FilterGroup />"
];
const result = [];
for (const entry of original) {
    if (result.length > 0) {
        result.push("<Conjunction />");
    }
    result.push(entry);
}
console.log(result);

(Yes, you can shoe-horn that into a reduce call, because any array operation can be shoe-horned into a reduce call, but it doesn't buy you anything.)

But if you want to modify an existing array, you can use splice:

for (let i = theArray.length - 1; i > 0; --i) {
    theArray.splice(i, 0, "<Conjunction />");
}

Example using strings instead of elements:

var theArray = [
    "<FilterGroup />",
    "<FilterGroup />",
    "<FilterGroup />",
    "<FilterGroup />"
];
for (let i = theArray.length - 1; i > 0; --i) {
    theArray.splice(i, 0, "<Conjunction />");
}
console.log(theArray);

Upvotes: 2

Related Questions