Home > Back-end >  copy array item and put in position-dependent by property value?
copy array item and put in position-dependent by property value?

Time:11-23

I have an array:

let rawArray = [{ name: "Name", repeat: null }, { name: "Name1", repeat: 2 }, ...];

I need to loop rawArray and read repeat property, if repeat is not equal to null, copy that item and repeat that item buy repeat times value?

How is that possible? :)

I want to have result as :

let result = [..., { name: "Name1", repeat: 2 }, ..., { name: "Name1", repeat: 2 } ... { name: "Name1", repeat: 2 }, ... etc];

CodePudding user response:

You can use flatMap

let rawArray = [{ name: "Name", repeat: null }, { name: "Name1", repeat: 2 }];

console.log(rawArray.flatMap(item => {
  const { repeat } = item
  
  if (repeat === null) {
    return [item] // or [] if you want to omit item w/o repeat
  }
  
  return Array.from({ length: repeat}).map(() => ({ ...item }))
}))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Normal HTML and js

<!DOCTYPE html>
<html>
    <head>  
    </head>
    <body>
        <ul id="myList">
        </ul>
        
        
    <script type="text/javascript">
    const rawArray = [
      { name: 'Name', repeat: null },
      { name: 'Name1', repeat: 2 },
      { name: 'Name2', repeat: 5 },
      { name: 'Name3', repeat: null },
    ]
    function my_code(){
        rawArray.map((item)=> {
            var node = document.createElement("LI");
            var textnode = document.createTextNode(item.name);
            node.appendChild(textnode);
            document.getElementById("myList").appendChild(node);
            if(item.repeat) {
                Array.from(Array(item.repeat).keys()).map((repeatItem) => {
                    var nodeRepeat = document.createElement("LI");
                    var textnodeRepeat = document.createTextNode(item.name '(repet' (repeatItem 1) ')');
                    nodeRepeat.appendChild(textnodeRepeat);
                    document.getElementById("myList").appendChild(nodeRepeat);
                    return null
                })              
            }
            return null
        })
    }

    window.onload=my_code();
    </script>
    </body>
</html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

react js

const rawArray = [
  { name: 'Name', repeat: null },
  { name: 'Name1', repeat: 2 },
  { name: 'Name2', repeat: 5 },
  { name: 'Name3', repeat: null },
]
const MyList= () => {
return (
<div>
{rawArray.map((item, i) => (
        <div key={i.toString}>
          {item.name}
          {item.repeat && (
            <>
              {Array.from(Array(item.repeat).keys()).map((repeatItem, r) => (
                <div key={r.toString}>
                  {item.name}
                  <i>- repeat {repeatItem   1}</i>
                </div>
              ))}
            </>
          )}
        </div>
      ))}
</div>
)
}
export default memo(MyList)

CodePudding user response:

You can use reduce:

const rawArray = [
  { name: "Name", repeat: null },
  { name: "Name1", repeat: 2 },
  { name: "Name2", repeat: 1 },
  { name: "Name3", repeat: 3 },
]

const result = rawArray.reduce((acc, item) => {
  if (!item.repeat) {
    return acc
  }
  
  return [
    ...acc,
    ...[...new Array(item.repeat)].map(i => item)
  ]
}, [])

console.log(result)

or with slightly less code:

const result = rawArray.reduce((acc, item) => (!item.repeat) ? acc : [
  ...acc,
  ...[...new Array(item.repeat)].map(i => item)
], [])
  • Related