Home > Back-end >  Find Unique value from an array based on the array's string value (Javascript)
Find Unique value from an array based on the array's string value (Javascript)

Time:10-24

so I want to find unique values from an array. so for example I have this array:

const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']

so I want to find the first matching value for each unique item. for example, in the array, I have two strings with the shape prefix, six items with the size prefix, and two items with the height prefix. so I want to output to be something like

const requiredVal = ["shape-10983", "size-2364", "height-3399"]

I want only the first value from any set of different values.

CodePudding user response:

the simplest solution will be to iterate on the list and storing what you got in a dictionary

function removeSimilars(input) {
    let values = {};
    for (let value of input) {//iterate on the array
        let key = value.splitOnLast('-')[0];//get the prefix
        if (!(key in values))//if we haven't encounter the prefix yet
            values[key] = value;//store that the first encounter with the prefix is with 'value'
    }
    return Object.values(values);//return all the values of the map 'values'
}

a shorter version will be this:

function removeSimilars(input) {
    let values = {};
    for (let value of input)
        values[value.splitOnLast('-')[0]] ??= value;
    return Object.values(values);
}

CodePudding user response:

You could split the string and get the type and use it aks key for an object along with the original string as value. At result take only the values from the object.

const
    data = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'],
    result = Object.values(data.reduce((r, s) => {
        const [type] = s.split('-', 1);
        r[type] ??= s;
        return r;
    }, {}));

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If, as you mentioned in the comments, you have the list of prefixes already available, then all you have to do is iterate over those, to find each first element that starts with that prefix in your full list of possible values:

const prefixes = ['shape', 'size', 'height'];
const list = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']

function reduceTheOptions(list = [], prefixes = [], uniques = []) {
  prefixes.forEach(prefix => 
    uniques.push(
      list.find(e => e.startsWith(prefix))
    )
  );
  return uniques;
}

console.log(reduceTheOptions(list, prefixes));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Try this:

function getRandomSet(arr, ...prefix)
{
  // the final values are load into the array result variable
  result = [];

  const randomItem = (array) => array[Math.floor(Math.random() * array.length)];
  prefix.forEach((pre) => {
    const r = arr.filter((par) => String(par).startsWith(pre));
    result.push(randomItem(r));
  });
  return result;
}


const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'];

console.log("Random values: ", getRandomSet(mainArr, "shape", "size", "height"));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

create a new array and loop over the first array and check the existing of element before in each iteration if not push it to the new array

  • Related