0

I have few arrays of JSON objects.I need to iterate over the arrays and return true if there are two or more elements with the same userId value.

[{
"name":"John",
"age":30,
"userId": 5,
}],

[{
"name":"Benjamin",
"age":17,
"userId": 5,
}],

[{
"name":"Johnatan",
"age":35,
"userId": 10,
}]

Here is my method so far, I'm iterating over the array and checking is there a user with 506 userId presence.

isPostedMultiple = (data) => {
 for (let j = 0; j < data.length; j++) {
   if (data[j].UserId == '506') {
    console.log('506 data :', data[j]);
   } else {
    console.log('not 506 data'); 
   }
 }
}
J.range
  • 449
  • 5
  • 20

5 Answers5

3

First of all the Object you have given is erroneous. Make it correct. Coming to the problem, You can use a combination of Array.prototype.some and Array.prototype.filter.

data.some(
  (el, i, arr) => arr.filter(_el => _el.userId == el.userId).length > 1
);

To check if there exists more than one element matching certain condition.

var data = [{
    "name": "John",
    "age": 30,
    "userId": 5,
  },
  {
    "name": "Benjamin",
    "age": 17,
    "userId": 5,
  },
  {
    "name": "Johnatan",
    "age": 35,
    "userId": 10,
  }
];

var result = data.some(
  (el, i, arr) => arr.filter(_el => _el.userId == el.userId).length > 1
);

console.log(result)
void
  • 36,090
  • 8
  • 62
  • 107
1

You can merge arrays using array spread syntax and than use the reduce with the filter method

const mergedArrays = [...arr1, ...arr2, ...arr3];
const isDublicated = mergedArrays.reduce(
  (acc, item) => acc || mergedArrays.filter(user => user.userId === item.userId) > 1,
  false
);
Piotr Białek
  • 2,569
  • 1
  • 17
  • 26
  • 1
    Please see [*Is …foo an operator or syntax?*](https://stackoverflow.com/questions/44934828/is-foo-an-operator-or-syntax) – RobG Mar 15 '18 at 21:07
  • Why not just use `[...arr1, ...arr2, ...arr3].filter((item, index, source) => source.some(u => u.userId === item.userId))`? Not sure what value `reduce` is adding? – sellmeadog Mar 15 '18 at 21:21
  • Note that this solution is for [ES6 or greater](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Browser_compatibility) and will not work in older browsers. – Jake Holzinger Mar 15 '18 at 21:27
  • @sellmeadog couse I didn't think about that solution, but you are right it's clearer. – Piotr Białek Mar 15 '18 at 21:33
  • This hard codes the number of source arrays (in this case, 3), creates an unnecessary additional array and loops over the resulting array up to length times (in this case, 3) so is inefficient. – RobG Mar 15 '18 at 21:44
0

To achieve expected result, use below option of using filter and findIndex to iterate over every array and compare userId

var x = [[{
"name":"John",
"age":30,
"userId": 5,
}],

[{
"name":"Benjamin",
"age":17,
"userId": 5,
}],

[{
"name":"Johnatan",
"age":35,
"userId": 10,
}]]

x = x.filter((v, i, self) =>
  i === self.findIndex((y) => (
     y[0].userId === v[0].userId
  ))
)


console.log(x);

code sample - https://codepen.io/nagasai/pen/wmWqdY?editors=1011

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
0

var jsonObj1 = [{
"name":"John",
"age":30,
"userId": 5
},

{
"name":"Benjamin",
"age":17,
"userId": 5
},

{
"name":"Johnatan",
"age":35,
"userId": 10
}];

var jsonObj2 = [{
"name":"John",
"age":30,
"userId": 5
},

{
"name":"Benjamin",
"age":17,
"userId": 15
},

{
"name":"Johnatan",
"age":35,
"userId": 10
}];

var logger = document.getElementById('logger');
logger.innerHTML = "";

function checkForDupIds(jsonObj, headerStr) {
  var logger = document.getElementById('logger');
  var hasDups = [];
  var items = [];
  for(var a=0;a<jsonObj.length;a++) {
    if (items.includes(jsonObj[a].userId)) {
      hasDups.push(jsonObj[a].userId);
    } else {
      items.push(jsonObj[a].userId);
    }
  }
  logger.innerHTML += "<h1>" + headerStr + "</h1>";
  for(var b=0;b<hasDups.length;b++) {
    logger.innerHTML += "<div>" + hasDups[b] + "</div>\n";
    console.log(hasDups[b]);
  }
  if (hasDups.length === 0) {
    logger.innerHTML += "<div>No Duplicates Found</div>\n";
  }
}

checkForDupIds(jsonObj1, "jsonObj1");
checkForDupIds(jsonObj2, "jsonObj2");
<html>
<body>
<div id='logger'></div>
</body>
</html>
Rick Riggs
  • 336
  • 2
  • 12
0

You can loop over the array and keep a count of how many times each userId value appears. If you get to 2 for any value, stop and return false (or some other suitable value).

Array.prototype.some allows looping over the array until the condition is true, so it only loops over the source once. The data in the OP was invalid, I've modified it to be an array of objects.

var data = [{
"name":"John",
"age":30,
"userId": 5
},
{
"name":"Benjamin",
"age":17,
"userId": 5
},
{
"name":"Johnatan",
"age":35,
"userId": 10
}]

function hasDupIDs(data) {
  // Store for userId values
  var ids = {};
  // Loop over values until condition returns true
  return data.some(function(x) {
    // If haven't seen this id before, add to ids
    if (!ids.hasOwnProperty(x.userId)) ids[x.userId] = 0;
    // Increment count
    ids[x.userId]++;
    // Return true if second instance
    return ids[x.userId] > 1;
  });
}

console.log(hasDupIDs(data));

If you want more concise code, you can use:

var data = [
  {"name":"John","age":30,"userId": 5},
  {"name":"Benjamin","age":17,"userId": 5},
  {"name":"Johnatan","age":35,"userId": 10}];

function hasDupIDs(data) {
  var ids = {};
  return data.some(x => {
    ids[x.userId] || (ids[x.userId] = 0);
    return ++ids[x.userId] > 1;
  });
}

console.log(hasDupIDs(data));
RobG
  • 142,382
  • 31
  • 172
  • 209
  • I think your assumption that the data in the original question is invalid is incorrect. I think the OP was clearly asking given N disparate arrays, how do I find duplicates between them which your answer does not do. However, your solution would obviously work after the source arrays have been concatenated. – sellmeadog Mar 16 '18 at 15:56
  • @sellmeadog—the OP's code contains syntax errors, so how is the statement "*The data in the OP was invalid*" incorrect? Another answer says the same thing. I guessed at a way to turn it into valid code, as have others. I posted this answer as I think it's much more efficient than others, particularly the accepted answer. – RobG Mar 17 '18 at 03:10
  • I am not arguing the OP's syntax errors, but that aside, I still believe the sample data was provided to indicate that the goal is to find duplicates across disparate, same-shaped arrays. It's entirely possible I'm wrong. – sellmeadog Mar 17 '18 at 06:28