0

How can I check if the two objects below have matching elements? If they have matching elements ..I would like to store the matching elements in an empty variable called var storeHere = [].

var one = ["2021-02-25", "2021-02-24", "2021-02-23", "2021-02-22", "2021-02-21", "2021-03-02", "2021-02-11", "2021-02-10"];
var two = ["2021-02-25", "2021-02-25", "2021-02-23"];

var storeHere = [];

So far I managed to match the two objects and get either a true or a false if there is a match but i would also like to store the matching values in an emtpy variable.

var one = ["2021-02-25", "2021-02-24", "2021-02-23", "2021-02-22", "2021-02-21", "2021-03-02", "2021-02-11", "2021-02-10"];
var two = ["2021-02-25", "2021-02-25", "2021-02-23"];

function ex (alldates, selected) {
    return selected.some(function (v) {
        return alldates.indexOf(v) >= 0;
    });
};
    ex(one, two);
  

2 Answers 2

1

You have a couple of options

You can use Array.filter:

const one = [
    "2021-02-25",
    "2021-02-24",
    "2021-02-23",
    "2021-02-22",
    "2021-02-21",
    "2021-03-02",
    "2021-02-11",
    "2021-02-10",
];

const two = [
    "2021-02-25",
    "2021-02-25",
    "2021-02-23",
];

// If an element is in two, include it. Otherwise, exclude it.
const storeHere = one.filter((date) => two.includes(date))

console.log(storeHere) // [ '2021-02-25', '2021-02-23' ]

Or you can use ES6 sets with Set.has:

const one = [
    "2021-02-25",
    "2021-02-24",
    "2021-02-23",
    "2021-02-22",
    "2021-02-21",
    "2021-03-02",
    "2021-02-11",
    "2021-02-10",
];

const two = new Set([
    "2021-02-25",
    "2021-02-25",
    "2021-02-23",
]);

// If an element is in two, include it. Otherwise, exclude it.
const storeHere = one.filter((date) => two.has(date))

console.log(storeHere) // [ '2021-02-25', '2021-02-23' ]

The advantage of the set is that it's faster, because it only contains unique elements (if any repeated elements exist). However, the difference is probably minor, since both solutions are basically the same thing.

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

Comments

1

You can do this

var one = ["2021-02-25", "2021-02-24", "2021-02-23", "2021-02-22", "2021-02-21", "2021-03-02", "2021-02-11", "2021-02-10"];
var two = ["2021-02-25", "2021-02-25", "2021-02-23"]; 
var storeHere = [];


one.forEach(date => {
   if(two.includes(date)) {
       storeHere.push(date);
   }
}

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.