-1
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) )
}
1

2 Answers 2

-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);

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

6 Comments

7 and 12 year duplicates.
@pilchard I feel like you missed the part about ignoring order.
pretty sure 'ignoring order' is covered in one of he 103 answers in the duplicate (in fact on the very first page of answers)
@pilchard That isn't the criteria for duplicates, but to each their own.
The number is just the example the array is array of strings....
|
-1

"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), {});
  for(const n of newArray){
    counts[n] = (counts[n] ?? 0) - 1
    if(counts[n] < 0){
      return false;
    }
  }
  return true;
}

array.forEach(arr => console.log(...arr, '=>', doesIncludesValuesFromArray(arr, newArray)));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.