1

I want to compare two array in that i want to change value of matching id.

Please refer bellow array's and result.

let array1 =[
  {
    "id": 1,
    "value": false
  },
  {
    "id": 2,
    "value": false
  },
  {
    "id": 3,
    "value": true
  },
  {
    "id": 4,
    "value": false
  }
]


let array2 = [
  {
    "id": 1
  },
  {
    "id": 4
  }
]

I want to use underscore library to compare this arrays and return the compare array value result as like below array

result = [
  {
    "id": 1,
    "value": true
  },
  {
    "id": 2,
    "value": false
  },
  {
    "id": 3,
    "value": true
  },
  {
    "id": 4,
    "value": true
  }
]

4 Answers 4

2

You can use Array.prototype.map():

const array1 =[{"id": 1,"value": false},{"id": 2,"value": false},{"id": 3,"value": true},{"id": 4,"value": false}]
const array2 = [{"id": 1},{"id": 4}]

const result = array1.map(({id, value}) => ({
  id,
  value: value || array2.some(item => item.id === id)
}))

console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

1

Another solution by using map

let array1 =[
  {
    "id": 1,
    "value": false
  },
  {
    "id": 2,
    "value": false
  },
  {
    "id": 3,
    "value": true
  },
  {
    "id": 4,
    "value": false
  }
]


let array2 = [
  {
    "id": 1
  },
  {
    "id": 4
  }
]

const resultArr = array1.map((item) => {
      if (array2.findIndex((item2) => {return item2.id == item.id}) !== - 1) {
          item.value = true;
      }
      return item; 
  })
  console.log(resultArr);

Comments

0

You can use lodash.map with lodash.some to check for object and update the value.

let array1 =[ { "id": 1, "value": false }, { "id": 2, "value": false }, { "id": 3, "value": true }, { "id": 4, "value": false } ],
    array2 = [ { "id": 1 }, { "id": 4 } ],
    result = _.map(array1, o => ({...o, value : _.some(array2, ({id}) => id === o.id) || o.value}));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Comments

0

You can try this:

array1.forEach(item => {
    item.value = item.value || array2.some(item2 => item2.id === item.id)
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.