Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

javascript - taking one element of each type from a list and only taking the first occurrence not working as expected

So this function is supposed to pars an array of object and only take the first occurrence of each type of object there is like 4 different ones and each ones has a dozen of entries.

    LastReadingOfEach(measurements){
        let devicesList = []
        devicesList.push(measurements.map((device) => {if (!devicesList.includes(device.Type) ) { return device} else console.log("removed :")}))
        console.log("devicesList : ", devicesList)
    }

I created an array and thought I could just push in a device of each type, but I think it doesn't compare against the array as it fill up because it at the end I find the devicesList has all elements on measurements

question from:https://stackoverflow.com/questions/66054866/taking-one-element-of-each-type-from-a-list-and-only-taking-the-first-occurrence

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe what you're looking for can be done with a reducer and findIndex. If find index fails to match the device type it will return -1, we know that we don't have that type yet so it gets pushed into the aggregation.

    LastReadingOfEach(measurements){
        const devicesList = measurements.reduce((agg, device) => {
          if (agg.findIndex(x => x.type === device.type) === -1) { 
            agg.push(device)
          } 
          return agg
        }, [])
        console.log("devicesList : ", devicesList)
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...