0

I'm trying to compare results from two different arrays containing similar strings;

Array1:

A350.1 - 2h 46 m
A210.2 - 3h 46 m

Array2:

A450.3 - 8h 0 m
A440.5 - 13h 0 m
A450.1 - 4h 0 m
A350.1 - 1h 45 m
A320.7 - 3h 45 m

So I would need to filter out A350.1 - 2h 46 m from Array1 since there's a similar object A350.1 - 1h 45 m in Array2

The results should look like this from the filtered array, only removing the object which has the identical name (in this example A350.1):

A210.2 - 3h 46 m

Any way I could do this effectively and push the results in a new filtered array?

3
  • Is it a string array? ["A350.1 - 2h 46 m", "A210.2 - 3h 46 m"]? or arrays with objects? Can you write down the exact array here in Javascript? Commented May 9, 2017 at 10:33
  • @sabithpocker I'm pushing these objects to an empty array (Array1, Array2) from a JSON response. Commented May 9, 2017 at 10:36
  • So if there is a conflict, item from array2 is taken always? Can you explain what you are trying to do here? Commented May 9, 2017 at 10:40

3 Answers 3

2

try this:

var arr1 = ["A350.1 - 2h 46 m", "A210.2 - 3h 46 m"]
var arr2 = ["A450.3 - 8h 0 m",
  "A440.5 - 13h 0 m",
  "A450.1 - 4h 0 m",
  "A350.1 - 1h 45 m",
  "A320.7 - 3h 45 m"
]
var firstPart = [];
arr1.forEach(function(obj1) {
  firstPart.push(obj1.substring(0, obj1.indexOf('-')))
});
arr2.forEach(function(obj2) {
  var i = firstPart.indexOf(obj2.substring(0, obj2.indexOf('-')));
  if (i !== -1)
    arr1.splice(i, 1);
});
console.log(arr1)

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

Comments

0

Make a loop that compare each values of Array1 against each values of Array2 and split your string like so array1[i].split("-"); to only compare the first part of your string

Comments

0

Prepare your lookup array by splitting off the interesting bit

var arr2_prepared = arr2.map(x => x.split(' - ')[0]);

Then filter out the elements from the data array that do not have the first part of their strings in the lookup array

var result = arr1.filter(x => arr2_prepared.indexOf(x.split(' - ')[0]) === -1);

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.