0

I'm trying to check if an array with multiple keys and values contains a duplicate if that's the case I don't want the duplicate to be pushed to the array.

Here's what I have so far (run inside a loop of items):

let positionArray = [], positionId="X", projectTitle="Title", xPosition=5, yPosition=10;
positionArray.push({
  "Id": positionId,
  "projectName": projectTitle,
  "xPosition": xPosition,
  "yPosition": yPosition
});
console.log($.inArray(positionId, positionArray));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Now all logic tells me that I should see something other than "-1" in the console when I run the loop, but it keeps returning "-1" every time. I have tried to figure out if it is simply because of .inArray() only works for arrays without a key, but no luck.

What am I doing wrong here?

im_tsm
  • 1,965
  • 17
  • 29
Morten K
  • 133
  • 4
  • which key determines the duplicate? `Id`? – im_tsm Nov 22 '18 at 09:23
  • Yes Id determines the dublicate :) – Morten K Nov 22 '18 at 09:24
  • In which case you need to search through the array of objects checking the `id` property of every item to find a match. See the duplicate I marked. Your current logic is flawed as you're looking for a string value within an array of objects, hence it will never make a match. – Rory McCrossan Nov 22 '18 at 09:25
  • @Rory Inside the loop I need to chack the array if an item with the same id is present in the arrray, if not it should push the item to the array else do nothing. I'll take a look at the suggested answer - I dodn't really know what to look for before I came here :) – Morten K Nov 22 '18 at 09:27
  • @MortenK You can use JS `some` method like: https://jsbin.com/wawovuhake/edit?js,console – im_tsm Nov 22 '18 at 09:37
  • The grep-approach suggested in the linked topic worked like a charm. Thanks! – Morten K Nov 22 '18 at 09:59
  • Please note the snippet I made and do that in the future too. It is really useful to have a [mcve] – mplungjan Nov 22 '18 at 10:24

1 Answers1

0

Regardless of your issue on inArray(), I would always suggest to use the prototype function of Array to find the index, i.e: findIndex():

let positionArray = [], positionId="X", projectTitle="Title", xPosition=5, yPosition=10;
positionArray.push({
  "Id": positionId,
  "projectName": projectTitle,
  "xPosition": xPosition,
  "yPosition": yPosition
});
var index = positionArray.findIndex(item => item.Id === positionId);
console.log(index);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62