0

I would like to remove the user id from the array(there are two of them)

const user = {
  "_id": "5d6caefdbb6f2921f45caf1d"
}

const allowners = [
  "5d6caefdbb6f2921f45caf1d",
  "5d6caee9bb6f2921f45caf1b",
  "5d6dfcd6e3b11807944348b8",
  "5d6caefdbb6f2921f45caf1d"
];

const vendors = []
allowners.forEach((allowner) => {
  if (allowner != user._id) {
    vendors.push(allowners)
  }
})
console.log(vendors, user._id)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
vithu shaji
  • 339
  • 3
  • 14
  • 1
    you can use filter instead of forEach – karthick Sep 06 '19 at 17:32
  • Can you format the example array a bit better? Like ```users = [["id1.1", "id2.1"],["id1.2", "id2.2"]]```? – VirxEC Sep 06 '19 at 17:33
  • See the linked question's answers, a simple `filter` does the job: `const vendors = allowners.filter(owner => owner !== user._id);`. – T.J. Crowder Sep 06 '19 at 17:34
  • I made you a [mcve] – mplungjan Sep 06 '19 at 17:36
  • 1
    If you want vendors to contain only unique IDs, you might want to consider `Set`s. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set – Codekie Sep 06 '19 at 17:36
  • TYPO: `vendors.push(allowner)` not `allowners` – mplungjan Sep 06 '19 at 17:37
  • @T.J.Crowder Code works just fine if he pushes what he passes - it is not a dupe but a typo – mplungjan Sep 06 '19 at 17:38
  • [ 5d6caefdbb6f2921f45caf1d, 5d6caee9bb6f2921f45caf1b, 5d6dfcd6e3b11807944348b8, 5d6caefdbb6f2921f45caf1d ] [ 5d6caefdbb6f2921f45caf1d, 5d6caee9bb6f2921f45caf1b, 5d6dfcd6e3b11807944348b8, 5d6caefdbb6f2921f45caf1d ] i am getting such a result @T.J.Crowder – vithu shaji Sep 06 '19 at 17:38
  • @vithushaji that is not a valid JS array. You need quotes. See the snippet I made for you. Please write such snippets in the future. It was much easier to see your mistake in a running example – mplungjan Sep 06 '19 at 17:39
  • Also you want `let vendors = []` since it is not a constant unless you filter or map the allowners into it – mplungjan Sep 06 '19 at 17:40
  • i concatinated two arrays and then it lost double quotes const allowners = Array.prototype.concat.apply([], owners) @mplungjan – vithu shaji Sep 06 '19 at 17:41
  • @mplungjan - Yes it is. `vendors` will always refer to the array. The fact the array is mutable has nothing to do with the declaration of `vendors`. – T.J. Crowder Sep 06 '19 at 17:44
  • `vendors.push(allowners)` is the typo - not pushing owner: `allowners.forEach(owner => { if (owner != user._id) { vendors.push(owner) } })` – mplungjan Sep 06 '19 at 17:44

0 Answers0