0

How to compare below array of strings and array of objects and spit out the values not matching in another array?

Array of strings:

["2018", "2017", "2016", "2015", "2014"]

Array of objects:

[ {"fiscalYear": "2018"},{"fiscalYear": "2017"},{"fiscalYear": "2016"}]

Expected result should be some another array of strings ["2015", "2014"].

Thanks!

3 Answers 3

3

You will need to filter values out of first array with the help of the second. Maybe like this:

const arr1 = ["2018", "2017", "2016", "2015", "2014"]
const arr2 = [{"fiscalYear": "2018"},{"fiscalYear": "2017"},{"fiscalYear": "2016"}]

const result = arr1.filter(val => !arr2.find(el => el.fiscalYear === val))

console.log(result)

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

Comments

1

If you are having problems with this, you might want to do it the old fashioned way to learn the basics.

var years = ["2018", "2017", "2016", "2015", "2014"];

objects = [ {"fiscalYear": "2018"},{"fiscalYear": "2017"},{"fiscalYear": "2016"}];

var yearsNotFound = [];

for (var i = 0; i < years.length; i++) {
    var found = false;
    for (var j = 0; j < objects.length; j++) {
        if (years[i] == objects[j].fiscalYear) {
            found = true;
            break;
        }
    }
    
    if (!found)
        yearsNotFound.push(years[i]);
}

console.log(yearsNotFound);

I would probably prefer the answer from @dfsq, but if you are a beginner I don't think it would hurt to look at how to do it with good old fashioned for loops. Knowing this will help you understand how to traverse different data structures in the future.

Comments

1

Basically @dfsq's answer, but without using arrow functions (ES6):

var years = ["2018", "2017", "2016", "2015", "2014"];
var fiscalYears = [ {"fiscalYear": "2018"},{"fiscalYear": "2017"},{"fiscalYear": "2016"}];

var filtered = years.filter(function(year1) {
  return !(fiscalYears.find(function(year2) {
    return (year2.fiscalYear === year1);
  }));
});

console.log(filtered);

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.