Saya ingin mengelompokkan kode pos dengan nilai duplikat. Saya memiliki array kode pos yang berisi duplikat.

var ArrayOfZipCodes = [{"zipCode" : "12345"},{"zipCode" : "24567"}, {"zipCode" : "24567"}, 
       {"zipCode" : "24567"} , {"zipCode" : "02895"} , {"zipCode" : "02861"} , {"zipCode" : "02895"}] 

Keluaran yang Dibutuhkan:

sorting the zipCodes and then grouping it.

var finalOutput = [{"zipCode" : "12345", from: "1"},{"zipCode" : "24567", from: "2 - 4"},
           {"zipCode" : "02861", from: "5"}, {"zipCode" : "02895", from: "6-7"} ] 

Inilah implementasi saya:

ArrayOfZipCodes.sort(function(a, b) {
    return a['zipCode'] - b['zipCode'];
});

ArrayOfZipCodes.forEach((item, index) => (item['id'] = index + 1));

const lookup = zipCodes.reduce((a, e) => {
    a[e['zipCode']] = ++a[e['zipCode']] || 0;
    return a;
}, {});

let group = ArrayOfZipCodes.filter(e => lookup[e['zipCode']]);

const filteredArr = group.reduce((acc, current, currentIndex, array) => {
    const x = acc.find(item => item['zipCode'] === current['zipCode']);
    if (x) {
        acc[0]['from'] = x['id'] + "-" + (array.length + 1);
    }
    return acc.concat([current]);

}, []);

var uniq = {}

var arrFiltered = ArrayOfZipCodes.filter(obj => !uniq[obj['zipCode']] && (uniq[obj['zipCode']] = true));

let finalArr = arrFiltered.concat(filteredArr);
console.log("finalArr", finalArr)

Ketika saya menjalankan, saya mendapatkan, [circular object Object] dan bukan output yang disebutkan di atas.

0
Thalapathy 29 Mei 2020, 07:31

1 menjawab

Jawaban Terbaik

Saya pikir ini harus melakukan apa yang Anda cari.

const arrayOfZipCodes = [
  {zipCode: "12345"},
  {zipCode: "24567"},
  {zipCode: "24567"},
  {zipCode: "24567"},
  {zipCode: "02895"},
  {zipCode: "02861"},
  {zipCode: "02895"},
];

const sortedZipCodes = arrayOfZipCodes.map(z => z.zipCode).sort();

const output = [...new Set(sortedZipCodes)].map(zipCode => {
  const first = sortedZipCodes.indexOf(zipCode);
  const last = sortedZipCodes.lastIndexOf(zipCode);
  const from = first === last ? `${first}` : `${first} - ${last}`;
  return {zipCode, from};
});

console.log(output);
1
Chase 29 Mei 2020, 04:51