Home > Software design >  How to check if array contains other array objects [JS]
How to check if array contains other array objects [JS]

Time:02-14

I'm trying to make a basic javascript algorithim. Im trying to make a basic 'enjoyability' scale. Basically if the array "tags", contains an object from "interests" add 1 to enjoyability. If the array "tags" contains an object from "dislikes" subtract 1 from enjoyability. How can I do this?

const fs = require('fs');
var interests = ["gaming", "coding", "dogs", "food"];
var dislikes = ["cats", "school", "work", "politics"];
var tags = ["gaming", "dogs", "school", "food", "coding"];
var enjoyability = 0;
var enjoyable = 0;
var PosOrNeg = 0;
var isIn;
const intr = tags.some(r=> interests.indexOf(r) >= 4)
const disl = tags.some(r=> dislikes.indexOf(r) >= 0)

if (intr == true) {
    console.log('a')
}

function run() {
    
console.log('a' enjoyability)
    console.log(tags.includes())
    if (enjoyability >= 0) {
        enjoyable = 0;
        console.log("yes")
    } else {
        enjoyable < 0;
        console.log("no")
    }
}
console.log(intr)
console.log(disl)
console.log(enjoyable)
run()

CodePudding user response:

for loop

const interests = ['gaming', 'coding', 'dogs', 'food'];
const dislikes = ['cats', 'school', 'work', 'politics'];

const tags = ['gaming', 'dogs', 'school', 'food', 'coding'];

let enjoyability = 0;

for (const tag of tags) {
    if (interests.find((item) => item === tag)) enjoyability  ;
    if (dislikes.find((item) => item === tag)) enjoyability--;
}

console.log(enjoyability);

CodePudding user response:

Perhaps this will help you:

var interests = ["gaming", "coding", "dogs", "food"];
var dislikes = ["cats", "school", "work", "politics"];
var tags = ["gaming", "dogs", "school", "food", "coding"];


function run() {
  var enjoyability = 0;
  for (let i = 0; i < tags.length; i  ) {
    const element = tags[i];

    if (interests.includes(element)) {
      enjoyability   // Add one
    } else if (dislikes.includes(element)) {
      enjoyability--; // Subtract one
    }
  }

  return enjoyability;
}

const output = run();

console.log(output);
  • Related