I have 2 arrays:
let array1 = ["a", "b", "c"]
const array2 = [{a: 23, b: 22, c: 14}, {a: 78, b: 22, c: 14}, {id: 3, a: 23, b: 80, c: 14}]
And I need update array1 according to the following conditions:
for each element from the array I need to return an object:
[{name: 'a', isDifferent: true}, {name: 'b', isDifferent: true}, {name: 'c', isDifferent: false}]
where isDifferent is true, for a given name, at least one value differs.
This is my function. It works.
But I think there are easier ways to do this.
array1 = array1.map(el => {
const newObj = {}
newObj.name = el
let isDifferent = false
for (let i = 0; i < array2.length; i++) {
if (array2[i][el] !== array2[0][el]) {
isDifferent = true
break
}
}
newObj.isDifferent = isDifferent
return newObj
})
Here's one method :
const array1 = ["a", "b", "c"] const array2 = [{a: 23, b: 22, c: 14}, {a: 78, b: 22, c: 14}, {id: 3, a: 23, b: 80, c: 14}] let result = array1.map( letter => { let values = array2.map(obj => obj[letter]); // Getting [23, 78, 3] for "a" return { name : letter, isDifferent : !values.every(v => v===values[0]) // Checks if every value in the array equals the first one } }) console.log(result)
You can take a look at javascript reduce
array method. reduce
const array2 = [{a: 23, b: 22, c: 14}, {a: 78, b: 22, c: 14}, {id: 3, a: 23, b: 80, c: 14}] const arr = array2.reduce((acc,curr)=>{ acc.push(curr.forEach(()=>{})) },[])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.