Saya punya array

data = [
{code: 'A1', name: 'bag', qty: 3},
{code: 'A2', name: 'purse', qty: 2},
{code: 'A3', name: 'belt', qty: 1},
]

Saya ingin menghilangkan qty & menduplikasi setiap item ke array lain berdasarkan masing-masing qty :

data = [
{code: 'A1', name: 'bag'},
{code: 'A1', name: 'bag'},
{code: 'A1', name: 'bag'},
{code: 'A2', name: 'purse'},
{code: 'A2', name: 'purse'},
{code: 'A3', name: 'belt'},
]

Saya sudah mencoba:

const [qtyList, setQtyList] = useState(
 new Array(renderData.length).fill(1)
);
const [selectedProduct, setSelectedProduct] = useState([])

const updatedQty = qtyList.map((q, index) => {
            if (index === k) return q = parseInt(val)
            else return q
        });
        setQtyList(updatedQty); //[3,2,1]

data.map((i, idx) => {
 let temp = []
 let existed = data.filter(x=>x.code==i.code).length
 for (let x=0; x<=qtyList[idx]; x++){
   temp.push(i)
 }
 setSelectedProduct((prev)=> [...prev, i])
}
0
vanio178 13 Januari 2022, 17:21

6 jawaban

Gunakan kode berikut:

var data = [
  { code: 'A1', name: 'bag', qty: 3 },
  { code: 'A2', name: 'purse', qty: 2 },
  { code: 'A3', name: 'belt', qty: 1 },
];

var newArray = data.map(x => {
  return Array(x.qty).fill({ code: x.code, name: x.name })
})

console.log([].concat.apply([], newArray))
3
Jeremy Thille 13 Januari 2022, 17:26

Pendekatan saya menggunakan pengurangan

let data = [
{code: 'A1', name: 'bag', qty: 3},
{code: 'A2', name: 'purse', qty: 2},
{code: 'A3', name: 'belt', qty: 1},
]

let a = data.reduce((acc,curr)=>{
    const {code,name,qty} = curr;
  for (let i = 0; i < qty; i++) {
    acc.push({code,name});
    }
  
  return acc;
},[])

console.log(a)
0
cmgchess 13 Januari 2022, 17:32

Mungkin ada solusi yang lebih elegan untuk masalah ini, tetapi ini adalah perbaikan cepat saya:

let data = [
{code: 'A1', name: 'bag', qty: 3},
{code: 'A2', name: 'purse', qty: 2},
{code: 'A3', name: 'belt', qty: 1},
]

let dupArr = []

data.map((i) =>{
   for(let j = 0;j<= i['qty']-1; j++){
       dupArr.push(i);
   }
});

dupArr.map((idx)=>{
    delete idx['qty'];
})

console.log(dupArr);
0
server-unknown 13 Januari 2022, 18:02
data.map(item => Array(item.qty).fill({ code: item.code, name: item.name })).flat();
0
Nalin Ranjan 13 Januari 2022, 17:36

Gunakan kode ini

data.reduce((a,{qty, ...rest})=>a.concat(Array(qty).fill({...rest})),[]);
0
Hafid Denguir 13 Januari 2022, 17:49

Contoh menggunakan flatMap

const data = [
    { code: "A1", name: "bag", qty: 3 },
    { code: "A2", name: "purse", qty: 2 },
    { code: "A3", name: "belt", qty: 1 },
];

const o = data.flatMap(({ code, name, qty }) =>
    Array(qty).fill({ code, name })
);

console.log(o);
0
ikhvjs 13 Januari 2022, 17:59