0

I have the following object:-

var list = {
  nums: [
    [117],
    [108]
  ],
  numsset: [
    [2256, 2265],
    [234],
    [3445, 3442]
  ]
};

If I had an input field on the page where a customer typed a number, how would I then be able to search the object for that value and return the key eg.

Input      Returned
108        nums
3445       numsset
2872       
2265       numsset

I have attempted looping through, but it didn't produce the required result.

Any help would be greatly appreciated, and thank you in advance.

1
  • 1
    "I have attempted looping through, but it didn't produce the required result." Show us that code and what it produced any maybe we can help you edit it. Commented Apr 5, 2018 at 15:50

2 Answers 2

1

Here is the working code:

const list = {
  nums: [
    [117],
    [108]
  ],
  numsset: [
    [2256, 2265],
    [234],
    [3445, 3442]
  ]
};

const findElement = (value) => {
  let foundKey = '';
  
  Object.keys(list).some((key) => {
    const array = list[key];
    
    const found = array.some(element => element.includes(value));
    
    if (found) {
    	foundKey = key;
      return true;
    }
    
    return false;
  })
  
  return foundKey;
}

console.log(findElement(2256));
console.log(findElement(108));
console.log(findElement(222));

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

1 Comment

ilsotov, how difficult would it be to change the code to say if it input starts with one of the values. E.g findElement(22562) would still return numsset as it starts with 2256.
0

You could build a hash table and store the keys of the given numbers.

var list = { nums: [[117], [108]], numsset: [[2256, 2265], [234], [3445, 3442]] },
    keys = {};

Object.keys(list).forEach(k => list[k].forEach(a => a.forEach(v => keys[v] = k)));

console.log(keys);

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.