Home > Blockchain >  Creating element for certain index in array - No Duplication
Creating element for certain index in array - No Duplication

Time:09-02

Lets say I have an array:

const array = [
  {
    id: 1,
    type: "A"
  },
  {
    id: 2,
    type: "B"
  },
  {
    id: 3,
    type: "A"
  }
]             // as you can see there are 2 times A. (*1)

And it goes like this...

const container = document.querySelector("container")

My child will go into container.

function anyFuction() {
  for (let i = 0; i < array.length; i  ) {
    Array.from(array[i][type]).forEach(() => {     //Here i cant reach the array(*2)
      const createButton = document.createElement("button");
      container.appendChild(createButton)
    })
  }
}

I am trying to get an element like a button for every type without duplicating it.

  1. There should be just 2 button for A and B not A again.
  2. This part makes me a bit sad.

CodePudding user response:

I modificated @Artur Niko 's answer. Much obliged!

const container = document.getElementById('container')
const values = [
{id: 1, type: 'A'},
{id: 2, type: 'B'},
{id: 3, type: 'A'},
{id: 4, type: 'C'}]

const newVals = {}
values.forEach(dataset => {
  if(!(Object.keys(newVals).includes(dataset.type))){
   newVals[dataset.type] = 1
  } 
}) 

Object.entries(newVals).forEach(dataset => {
  const key = dataset[0]
  const value = dataset[1]

  for(let i = 0; i < value; i  ){
   const button = document.createElement('button')
   button.innerText =`${key} `
   container.appendChild(button)
  }
  
})
<div id="container"></div>

CodePudding user response:

I am not exactly sure but I guess you want something like this:

const container = document.getElementById('container')
const values = [
{id: 1, type: 'A'},
{id: 2, type: 'B'},
{id: 3, type: 'A'},
{id: 4, type: 'C'}]

const newVals = {}
values.forEach(dataset => {
  if(!(Object.keys(newVals).includes(dataset.type))){
    newVals[dataset.type] = 1
  }
  else newVals[dataset.type]  
})

Object.entries(newVals).forEach(dataset => {
  const key = dataset[0]
  const value = dataset[1]
  
  const p = document.createElement('p')
  p.innerText = `${key}: `
  for(let i = 0; i < value; i  ){
    const button = document.createElement('button')
    p.appendChild(button)
  }
  container.appendChild(p)
})
<html>
  <head>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>

EXPLANATION: Here I am just rearranging passed data into new object and count types amount. The type goes as a key and amount as a value. The value I use to generate the buttons for each type.

  • Related