skip to Main Content
const array = 
[
[1,2,3],
[4,1,1,3]
[5,5,7]
]
const newArray = [2,3,1]

How I can find with javascript if this array exists in the array (exists with other order)

I sloved this by sort the array
and check with JSON.stringify

    let conflictIds = [...conflictsList.map(c=>c._id), ssdst._id]
            conflictIds =  conflictIds.sort();
        if(!existsInArray(conflictsArr, conflictIds)){
            const conflictObj = {schedules:conflictIds   .... }
    conflictsArr.push(conflictObj)
                                        }
                
const existsInArray = (array, newElement)=>{
return array.find(arr=>JSON.stringify(arr.schedules) ===JSON.stringify(newElement) )
}

3

Answers


  1. You can calculate the frequencies of elements in each array and compare them.

    const array = [
      [1, 2, 3],
      [4, 1, 1, 3],
      [5, 5, 7]
    ];
    const newArray = [2, 3, 1];
    const getFreq = arr => {
      const freq = new Map;
      for (const x of arr) freq.set(x, 1 + freq.get(x) || 1);
      return freq;
    };
    const newArrFreq = [...getFreq(newArray)];
    let found = array.some(arr => {
      const currFreq = getFreq(arr);
      return currFreq.size === newArrFreq.length && 
        newArrFreq.every(([k, v]) => v === currFreq.get(k));
    });
    // use find instead of some to get the actual array that matched
    console.log(found);
    Login or Signup to reply.
  2. "array in array" means that the second array could be bigger. To find the result we need collect counts of values and then substract counts from the first array. If there’s any negative count value that means that the second array doesn’t contain all values to recreate the first array:

    const array = [
      [1, 2, 4, 2, 3],
      [4, 1, 1, 3],
      [5, 5, 7]
    ];
    
    const newArray = [3, 2, 1, 2];
    
    function doesIncludesValuesFromArray(arr, newArray){
      if(newArray.length > arr.length) return false;
      const counts = arr.reduce((r, n) => (r[n] = (r[n] ?? 0) + 1, r), {});
      newArray.forEach(n => counts[n] = (counts[n] ?? 0) - 1);
      return !Object.values(counts).some(n => n < 0);
    }
    
    array.forEach(arr => console.log(...arr, '=>', doesIncludesValuesFromArray(arr, newArray)));
    Login or Signup to reply.
  3. const array = [
      [1, 2, 3],
      [4, 1, 1, 3],
      [5, 5, 7]
    ];
    const newArray = [2, 3, 1];
    const getFreq = arr => {
      const freq = new Map;
      for (const x of arr) freq.set(x, 1 + freq.get(x) || 1);
      return freq;
    };
    const newArrFreq = [...getFreq(newArray)];
    let found = array.find(arr => {
      const currFreq = getFreq(arr);
      return currFreq.size === newArrFreq.length && 
        newArrFreq.every(([k, v]) => v === currFreq.get(k));
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search