简体   繁体   中英

find all digits in a given Array with javascript

so I need to find all digits from 1 to 9 in a given array with javascript.

Example findAllDigits([5175, 4538, 2926, 5057, 6401, 4376, 2280, 6137, 8798, 9083] returns the last number it checked when found all 1 to 9 numbers. which in this case 5057 if a given array don't have all numbers from 1 to 9 then it returns "missing digits".

I don't even know how to approach it, hope you can help.

thanks

You could take a Set and collect all digits/characters of stringified numbers.

For returnung the wanted last number, you could use Array#find and check if the size of the set is ten.

 const findAllDigits = array => array.find((digits => value => { [...value.toString()].forEach(Set.prototype.add, digits); return digits.size === 10; })(new Set)); console.log(findAllDigits([5175, 4538, 2926, 5057, 6401, 4376, 2280, 6137, 8798, 9083])); // 5057

let data = [123456789, 41358, 2926, 1017];
let filled = [];
const findAllDigits = (array) => {
  for (let index = 0; index < array.length; index++) {
    const n = array[index];
    let arr = Array.from(String(n), Number);
    filled = [...filled, ...arr];
    let len = [...new Set(filled)].length;
    if (len === 9) return array[index +1];
  }
  let missing = [];
  for (let index = 1; index <= 9; index++) {
    if (!filled.includes(index)) {
      missing.push(index);
    }
  }
  return Number(missing.toString());
};

console.log(findAllDigits(data));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM