1

I have two arrays. Here's the first:

$scope.selection = {
  "carrots",
  "celery",
  "corn",
  "apples",
  "bananas"
};

Here's the second:

$scope.shipment = [{
    "id": "0",
    "name": "vegetables",
    "manifest": [{"carrots", "celery", "corn"}]
  }, {
    "id": "1",
    "name": "produce",
    "manifest": [{"apples", "carrots", "bananas"}]
}];

I'd like to be able to see if a match exists in the second array as I iterate through the first. So far, I can use jQuery inArrayto match an indexed item in the second array:

if ($.inArray($scope.shipment.manifest[0], $scope.selection) < 0) { console.log($scope.shipment.id) };

// for "carrots"
=> "0"

But since "carrots" is in two index positions in the shipment array, the above will only return the first shipment id.

How can I get both shipments?

1
  • You could use the .filter function in javascript. That will return all elements matching your expression Commented Sep 25, 2015 at 15:01

2 Answers 2

1

First of all, your object selection is not valid.

Objects are key-value pairs, and you only have strings insde it. It probably should be an array.

Second, the same happens with the objects inside the property manifest. They also must be arrays.

When fixing your code, you can use Array.prototype.filter to achieve what you want:

var result = $scope.shipment.filter(function(obj) {
  return obj.manifest.indexOf(item) >= 0;
});

Look at the snipped I've created below:

var $scope = {};

$scope.selection = [
  "carrots",
  "celery",
  "corn",
  "apples",
  "bananas"
];

$scope.shipment = [{
    "id": "0",
    "name": "vegetables",
    "manifest": ["carrots", "celery", "corn"]
  }, {
    "id": "1",
    "name": "produce",
    "manifest": ["apples", "carrots", "bananas"]
}];

var html = '';

$scope.selection.forEach(function(item, i) {
  var result = $scope.shipment.filter(function(obj) {
    return obj.manifest.indexOf(item) >= 0;
  });
  
  html +=
    '<div>' +
      '<span>Item: ' + item + '</span>' + 
    '</div>' +
    '<div>' +
      '<pre>' + JSON.stringify(result, null, 2) + '</pre>' +
    '</div>';
});

document.body.innerHTML = html;

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

1 Comment

Thanks. This helped me realize what I was missing.
0

$scope.shipment is an array that doesn't have a property manifest but the elements of that array are objects that do have that property

Try

$.inArray($scope.shipment[0].manifest[0], $scope.selection)

As mentioned there are simpler ways but I wanted to point out the problem

1 Comment

This kept getting me back to the same issue I had before. It was only calling the first manifest.

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.