Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding items from and array of obects based on a selected item value in JS

I have a an array like this:

var array = [
    { name:"string123", value:"this", other: "that" },
    { name:"string2", value:"this", other: "that" },
    { name:"string12", value:"ths", other: "that" },
];

And now I have a string like ‘string12’. Now with this string the output I want is to find the items that contains this string which is like:

var array = [
    { name:"string123", value:"this", other: "that" },
    { name:"string12", value:"ths", other: "that" },
];

Here’s what I have tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const search = (nameKey, myArray) => {
  for (var i = 0; i < myArray.length; i++) {
    var newArr = [];
    if (myArray[i].name.slice(0, nameKey.length + 1) === nameKey) {
      newArr.push(myArray[i]);
    }
    return newArr;
  }

}

var array = [
  { name:"string123", value:"this", other: "that" },
  { name:"string2", value:"this", other: "that" },
  { name:"string12", value:"ths", other: "that" },
];

var resultObject = search("string12", array);
console.log(resultObject);

But my solution is returning blank array. Where am i going wrong with this?

>Solution :

The following things went wrong in your implementation:

  1. Move initialization outside the for loop.
  2. You don’t need +1 when doing .slice().
  3. Return statement return newArr should be outside the for loop.
const search = (nameKey, myArray) => {
    var newArr = [];
  
  for (var i = 0; i < myArray.length; i++) {
    if (myArray[i].name.slice(0, nameKey.length) === nameKey) {
      newArr.push(myArray[i]);
    }
  }
    return newArr;
}

var array = [
  { name:"string123", value:"this", other: "that" },
  { name:"string2", value:"this", other: "that" },
  { name:"string12", value:"ths", other: "that" },
];

var resultObject = search("string12", array);
console.log(resultObject);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading