Home > Enterprise >  checking array if has same value
checking array if has same value

Time:05-23

Learning by coding, here i have an array of objects (data), and nodeId which is number , i want to check if that arrays 'target' has same value as nodeId then 'return', should i use map(), find(), filter(), how should i know which to use ? english is not my mother language so could be mistakes

data:

  const Test = '7'
const nodeId = parseInt(Test);

  
  const data = [
    { target: 4, name: "usa" },
    { target: 7, name: "England" },
    { target: 3, name: "Japan" }
  ];
  
  
   if (check if data and nodeId both have same value then) {
    return;
  }

CodePudding user response:

.some() is probably what you want to use

const check = data.some((elem) => elem.target === nodeId) 
console.log(check) // true if exist or false if it doesnt
if(check) {
  // reached if it exist
}

check would be false if it doesn't exist or true if it does. It will stop running once it finds a match whereas .filter() and .map() would run the entire array. If you also want to get the element then you should use .find() instead.

CodePudding user response:

Your question is a little vague but i'm going to try and answer it as easily as possible.

should i use map(), find(), filter(), how should i know which to use ?

That depends on what your hypothetical function or code would require, for example if you want the item that matched your value, then you would use .find() because it returns single value based on a condition.

similarly if you wish to return an array based on items that match the conditions, you would use .filter(), and same if you just want to check if your value exists in the array, you could use .some or .every.

in your code example, I'm assuming you want to return the specific value that matched with your nodeId, with that assumption, here's how that will work

function getDataBasedOnNodeId (dataObjects, matchValue) { 
 return dataObjects.find(item => item.target === Number(matchValue))
}

const data = [
    { target: 4, name: "usa" },
    { target: 7, name: "England" },
    { target: 3, name: "Japan" }
];
  

return getDataBasedOnNodeId(data, 7)
  • Related