0

I have an array of objects such as:

const array = [<Button>abc</Button>, <Button>def</Button>]

where when I render them with:

return array

I get a list of buttons next to each other.

something similar to the top line of this example picture:

example

However I want to join the buttons so it look like the bottom line. I tried to use array.join("+") but that no longer rendered buttons instead rendering <object object>+<object object>

Is it possible to do this? keep in mind the array needs to be looped to include all items and ideally it knows not to add a + to the last element.

1
  • Do you want 2 buttons with a "+" between them? A single button with the button text concatenated with a "+"? No button but just the button text concatenated with a "+"? Can you be a bit more explicit with the expected result? Commented Nov 14, 2020 at 0:57

2 Answers 2

1

Its a tricky use-case. I was able to achieve writing conditional inside map function.

  {array.map((item, index) => {
    if (index === array.length - 1) {
      return item;
    }
    return [item, "+"];
  })}

Here's working example link: https://stackblitz.com/edit/react-hceymc

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

Comments

0

Try This

var btns = document.querySelectorAll("button");
var btnArray = [], btnString = "";

btns.forEach(curr => {
    btnArray.push(curr);
});

btnArray.forEach(curr =>{
    btnString += curr.innerText + "+";
});

btnString = btnString.substring(0, btnString.length - 1);
console.log(btnString);

A simpler method using join() would look like this

var btns = document.querySelectorAll("button");
var btnArray = [], btnText = [], btnString = "";

btns.forEach(curr => {
    btnArray.push(curr);
});

btnArray.forEach(curr =>{
    btnText.push(curr.innerText);
});

btnString = btnText.join(" + ");
console.log(btnString);

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.