Home:ALL Converter>Compare array of strings with another array

Compare array of strings with another array

Ask Time:2017-01-18T05:40:41         Author:Mitesh

Json Formatter

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!

Author:Mitesh,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/41707507/compare-array-of-strings-with-another-array
dfsq :

You will need to filter values out of first array with the help of the second. Maybe like this:\n\n\r\n\r\nconst arr1 = [\"2018\", \"2017\", \"2016\", \"2015\", \"2014\"]\r\nconst arr2 = [{\"fiscalYear\": \"2018\"},{\"fiscalYear\": \"2017\"},{\"fiscalYear\": \"2016\"}]\r\n\r\nconst result = arr1.filter(val => !arr2.find(el => el.fiscalYear === val))\r\n\r\nconsole.log(result)",
2017-01-17T22:01:27
GantTheWanderer :

If you are having problems with this, you might want to do it the old fashioned way to learn the basics.\n\n\r\n\r\nvar years = [\"2018\", \"2017\", \"2016\", \"2015\", \"2014\"];\r\n\r\nobjects = [ {\"fiscalYear\": \"2018\"},{\"fiscalYear\": \"2017\"},{\"fiscalYear\": \"2016\"}];\r\n\r\nvar yearsNotFound = [];\r\n\r\nfor (var i = 0; i < years.length; i++) {\r\n var found = false;\r\n for (var j = 0; j < objects.length; j++) {\r\n if (years[i] == objects[j].fiscalYear) {\r\n found = true;\r\n break;\r\n }\r\n }\r\n \r\n if (!found)\r\n yearsNotFound.push(years[i]);\r\n}\r\n\r\nconsole.log(yearsNotFound);",
2017-01-17T22:13:42
yy