I have the next situation in my react application:
I have a state:
const [arr1, setArr1] = useState([1, 2, 3, 5, 1, 3]);
Bellow i render all items from array on UI like:
arr1.map(i => <li>{i}</li>)
Now i want to remove all items that are equal in the array:
ex:
[1, 2, 3, 5, 1, 3] // should be deleted 1 and 3 result: [1, 2, 5]
[1, 2, 3, 5, 3] // should be deleted 3 result: [1, 2, 5]
Deleting all items also the state should change here arr1.map().
I tried setArr1([new Set(arr1)]), but it does not delete all duplicated values, it delete just one of them.
How to achieve what i described above?
You can count the frequency of number and then just pick the number whose frequency is 1.
const arr = [1, 2, 3, 5, 1, 3],
frequency = arr.reduce((o,v) => (o[v] = (o[v] || 0) + 1, o), {}),
unique = Object.keys(frequency).reduce((r,k) => frequency[k] === 1? [...r, +k]: r, []);
console.log(unique);
Check if the the first index equal to the last index on an element,when they are equals it means it is unique:
let result = []
let arr = [1, 2, 3, 5, 1, 3]
arr.forEach(e => arr.indexOf(e) === arr.lastIndexOf(e)?result.push(e):null)
console.log(result)
You can calculate the frequency and remove the number if the frequency is greater than 1. codesandbox
function removeDuplicates(arr) {
const frequency = {};
arr.forEach((el) => {
frequency[el] = frequency[el] ? ++frequency[el] : 1;
});
const result = [];
for (el in frequency) {
if (frequency[el] === 1) {
result.push(el);
}
}
return result;
}
const arrayWithoutDuplicates = removeDuplicates(arr1);
return (
<ul>
{arrayWithoutDuplicates.map((el) => {
return <li key={el}> {el} </li>;
})}
</ul>
);
Below is a one-liner using filter
const arr = [1, 2, 3, 5, 1, 3];
const unique = arr.filter(x => arr.filter(y => y === x).length < 2)
console.log(unique);
Related
I need to check whether one array contains all of the elements of another array, including the same duplicates. The second array can have extra elements. I'm using every...includes, but it's not catching that the second array doesn't have the right duplicates.
For example:
const arr1 = [1, 2, 2, 3, 5, 5, 6, 6]
const arr2 = [1, 2, 3, 5, 6, 7]
if(arr1.every(elem => arr2.includes(elem))){
return true // should return false because arr2 does not have the same duplicates
}
Thanks!
Edit: arr1 is one of many arrays that I am looping through which are coming out of a graph traversal algorithm, so I'd like to avoid restructuring them into an object to create a dictionary data structure if possible.
Try creating this function:
function containsAll (target, toTest) {
const dictionary = {}
target.forEach(element => {
if (dictionary[element] === undefined) {
dictionary[element] = 1;
return;
}
dictionary[element]++;
});
toTest.forEach(element => {
if (dictionary[element] !== undefined)
dictionary[element]--;
})
for (let key in dictionary) {
if (dictionary[key] > 0) return false;
}
return true;
}
Then invoke it like this:
const arr1 = [1, 2, 2, 3, 5, 5, 6, 6]
const arr2 = [1, 2, 3, 5, 6, 7]
console.log(containsAll(arr1, arr2)) // returns false
const arr1 = [1, 2, 2, 3, 5, 5, 6, 6];
//const arr2 = [1, 2, 3, 5, 6, 7];
const arr2 = [1, 2, 2, 3, 5, 5];
let includesAll1 = true;
let includesAll2 = true;
const checkObj1 = {
};
const checkObj2 = {
};
arr1.forEach((el)=> {
if(checkObj1[el] === undefined) {
checkObj1[el] = 1;
} else {
checkObj1[el]++;
}
});
arr2.forEach((el)=> {
if(checkObj2[el] === undefined) {
checkObj2[el] = 1;
} else {
checkObj2[el]++;
}
});
const check1Keys = Object.keys(checkObj1);
const check2Keys = Object.keys(checkObj2);
if(check1Keys.length > check2Keys.length) {
includesAll2 = false;
check2Keys.forEach((key)=> {
const value1 = checkObj1[key];
const value2 = checkObj2[key];
if(!arr1.includes(parseInt(key)) || value1 != value2) {
includesAll1 = false;
}
});
} else {
includesAll1 = false;
check1Keys.forEach((key)=> {
const value1 = checkObj1[key];
const value2 = checkObj2[key];
console.log(value1, value2, key);
if(!arr2.includes(parseInt(key)) || value1 != value2) {
includesAll2 = false;
}
});
}
console.log(includesAll1);
console.log(includesAll2);
Does this solve your problem?
const arr = [1, 2, 3, 5, 6, 7, 2, 10, 2, 3, 2];
const subArr = [1, 2, 2, 3, 2]
const contains = subArr.every(num => subArr.filter(n => n == num).length <= arr.filter(n => n== num).length);
console.log(contains);
You indicate order does not matter in your comments. That makes this very simple.
Sort both arrays
Check if corresponding elements are equal
consider errors associated with sparse or short arrays
Use .reduce() to boil it down to a single result
So this really comes down to a single statement once the arrays are sorted:
matcher.reduce((acc, value , idx)=>matcher[idx] === test[idx], false);
You also mentioned testing this against many arrays. So the full example below does that for demo purposes.
let toMatch = [1, 2, 2, 3, 5, 5, 6, 6]
let arrayOfArrays = [[1,2],[1, 2, 3, 5, 6, 7, 3, 9, 8, 2, 7],[1, 2, 3, 3, 6, 7],[1, 3, 3, 5, 6, 7],[1, 2, 3, 5, 6, 6], [3,5,2,1,6,2,5,6]];
let toMatchSorted = toMatch.slice().sort();
arrayOfArrays.forEach(arr=>{
let toTestSorted = arr.slice().sort();
let out = toMatchSorted.reduce((acc, value , idx)=>toMatchSorted[idx] === toTestSorted[idx], false);
console.log(`Input: ${arr}, Result: ${out}`);
});
I am trying this solution but it is not giving me the result I want.
I don't want to count the number of pairs of 1 cause it is not really a pair as it appears 4 times.
I need to count the "perfect" pairs, like in this case: 5 and 2. Right now this is giving me 4 as result and it should be 2.
How could I achieve that? I am stuck.
let ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2];
const countPairs = (ar) => {
let obj = {};
ar.forEach((item) => {
obj[item] = obj[item] ? obj[item] + 1 : 1;
});
return Object.values(obj).reduce((acc, curr) => {
acc += Math.floor(curr / 2);
return acc;
}, 0);
};
console.log( countPairs(ar1) )
You can filter the object values by 2 and count the list
let ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2];
const countPairs = (ar) => {
let obj = {};
ar.forEach((item) => {
obj[item] = obj[item] ? obj[item] + 1 : 1;
});
return Object.values(obj).filter(e => e == 2).length;
};
console.log(countPairs(ar1))
This can be one-liner using Map as:
const countPairs(arr) => [...arr.reduce((dict, n) => dict.set(n, (dict.get(n) ?? 0) + 1), new Map()).values(),].filter((n) => n === 2).length;
let ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2];
const countPairs = (arr) =>
[
...arr
.reduce((dict, n) => dict.set(n, (dict.get(n) ?? 0) + 1), new Map())
.values(),
].filter((n) => n === 2).length;
console.log(countPairs(ar1));
or that
const
ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2]
, countPerfectPairs = arr => arr.reduce((r,val,i,{[i+1]:next})=>
{
if(!r.counts[val])
{
r.counts[val] = arr.filter(x=>x===val).length
if (r.counts[val]===2) r.pairs++
}
return next ? r : r.pairs
},{counts:{},pairs:0})
console.log( countPerfectPairs(ar1) )
If you prefer Details:
const
ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2]
, countPerfectPairs = arr => arr.reduce((r,val)=>
{
if(!r.counts[val])
{
r.counts[val] = arr.filter(x=>x===val).length
if (r.counts[val]===2) r.pairs++
}
return r
},{counts:{},pairs:0})
console.log( countPerfectPairs(ar1) )
We have an Array of arrays, which we want to interleave into a single array:
i.e:
masterArray = [[1, 2, 3], ['c', 'd', 'e']] => [1, 'c', 2, 'd', 3, 'e'],
if arrays are not of equal length, pad it to the longest innerArray's length.
i.e
[1, 2, 3], [4, 5]) => [1, 4, 2, 5, 3, null]
I've satisfied this condition with the case of 2 arrays, however if the case is more than that. I struggle to form a strategy on dealing with more than 2.
[1, 2, 3], [4, 5, 6], [7, 8, 9] => [1, 4, 7, 2, 5, 8, 3, 6, 9]
function interleave(...masterArray) {
let rtnArray = [];
let longestArrayPosition = getLongestArray(masterArray);
let longestInnerArrayLength = masterArray[longestArrayPosition].length;
padAllArraysToSameLength(masterArray, longestInnerArrayLength); //pad uneven length arrays
masterArray[0].forEach((firstArrayNum, index) => {
const secondArrayNum = masterArray[1][index];
rtnArray.push(firstArrayNum);
rtnArray.push(secondArrayNum);
});
return rtnArray;
}
function getLongestArray(masterArray) {
return masterArray
.map(a=>a.length)
.indexOf(Math.max(...masterArray.map(a=>a.length)));
}
function padAllArraysToSameLength(masterArray, maxLength) {
return masterArray.forEach(arr => {
if (arr != maxLength) {
while(arr.length != maxLength) {
arr.push(null);
}
}
})
}
Use Array.from() to transpose the array of arrays (rows => columns and vice versa), and fill in the missing places with null. Flatten the tramsposed arrays of arrays with Array.flat():
const fn = arr => Array.from({
length: Math.max(...arr.map(o => o.length)), // find the maximum length
},
(_, i) => arr.map(r => r[i] ?? null) // create a new row from all items in same column or substitute with null
).flat() // flatten the results
const arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
const result = fn(arr)
console.log(result)
You can do this for any number of arrays with two nested forEach statements:
let arr1 = [[1,2,3],[4,5]]
let arr2 = [[1,2,3], [4,5,6], [7,8,9]]
let arr3 = [[1,2,3,4], [4,5,6], [7,8,9], [10,11,12]]
function interLeaveArrays(mainArr){
let maxLen = Math.max(...mainArr.map(arr => arr.length))
mainArr.forEach(arr => {
let lenDiff = maxLen - arr.length
for(let i=lenDiff; i>0; i--){
arr.push(null)
}
})
let newArr = []
mainArr.forEach((arr, idx1) => {
arr.forEach((el, idx2) => {
newArr[idx2 * mainArr.length + idx1] = el
})
})
return newArr
}
console.log(interLeaveArrays(arr1))
console.log(interLeaveArrays(arr2))
console.log(interLeaveArrays(arr3))
Let's say I have an array such as: [1, 1, 2, 2, 3, 3, 4, 5]
And I want to remove this array of elements [1, 2, 3, 4, 5]
So in the end I want to be left with [1, 2, 3]
I have tried using the method below but it removes all copies of the elements from the main array.
myArray = myArray.filter( function( el ) {
return !toRemove.includes( el );
} );
Here is a way to do it using filter, indexOf and splice.
const input = [1, 1, 2, 2, 3, 3, 4, 5];
function removeSubset(arr, subset) {
const exclude = [...subset];
return arr.filter(x => {
const idx = exclude.indexOf(x);
if (idx >= 0) {
exclude.splice(idx, 1);
return false;
}
return true;
});
}
console.log(removeSubset(input, [1, 2, 3, 4, 5]));
You could get a Map and count the values and filter by checking the count and decrement the count if found.
var array = [1, 1, 2, 2, 3, 3, 4, 5],
remove = [1, 2, 3, 4, 5],
map = remove.reduce((m, v) => m.set(v, (m.get(v) || 0) + 1), new Map),
result = array.filter(v => !map.get(v) || !map.set(v, map.get(v) - 1));
console.log(result);
One solution is looping on the array of elements to remove and for each one remove the first element found on the input array:
const input = [1, 1, 2, 2, 3, 3, 4, 5];
const removeItems = (input, items) =>
{
// Make a copy, to not mutate the input.
let clonedInput = input.slice();
// Search and remove items.
items.forEach(x =>
{
let i = clonedInput.findIndex(y => y === x);
if (i >= 0) clonedInput.splice(i, 1);
});
return clonedInput;
}
console.log(removeItems(input, [1,2,3,4,5]));
console.log(removeItems(input, [1,2]));
console.log(removeItems(input, [1,99,44,5]));
If you still want to use filter, you can use the items to remove as the this argument of the filter, something like this:
const input = [1, 1, 2, 2, 3, 3, 4, 5];
const removeItems = (input, items) =>
{
return input.filter(function(x)
{
let i = this.findIndex(y => y === x);
return i >= 0 ? (this.splice(i, 1), false) : true;
}, items.slice());
}
console.log(removeItems(input, [1,2,3,4,5]));
console.log(removeItems(input, [1,2]));
console.log(removeItems(input, [1,99,44,5]));
You can use Filter and Shitf and Sort
let arr = [1, 1, 2, 2, 3, 3, 4, 5]
let remove = [1, 3, 2, 4, 5].sort((a,b)=>a-b)
let op = arr.sort((a,b)=>a-b).filter(e => ( remove.includes(e) ? (remove.shift(), false) : true ))
console.log(op)
Having an array of numbers setOfNumbers = [0, 3, 3, 2, 7, 1, -2, 9] I'd like to sort this set to have the smallest numbers on the end and beginning and the biggest in the center of the sorted set like this sortedSetNumbers = [0, 2, 3, 9, 7, 3, 1, -2].
const setOfNumbers = [0, 3, 3, 2, 7, 1, -2, 9];
const result = [0, 2, 3, 9, 7, 3, 1, -2];
function sortNormal(a, b) {
return true; // Please, change this line
}
const sortedSetNumbers = setOfNumbers.sort((a, b) => sortNormal(a, b));
if (sortedSetNumbers === result) {
console.info('Succeeded Normal Distributed');
} else {
console.warn('Failed Normal Distribution');
}
console.log(sortedSetNumbers);
I am sure it is possible to sort these numbers with the method Array.prototype.sort(), but how should this sorting function look like?
EDIT: The solution does not have to be solved with .sort(). That was only an idea.
This might be the most naive way to do it, but isn't it simply left, right, left, right... after sorting?
const input = [0, 3, 3, 2, 7, 1, -2, 9];
const expected = [0, 2, 3, 9, 7, 3, 1, -2];
const sorted = input.slice().sort();
const output = [];
let side = true;
while (sorted.length) {
output[side ? 'unshift' : 'push'](sorted.pop());
side = !side;
}
console.log(expected.join());
console.log(output.join());
Or simply:
const input = [0, 3, 3, 2, 7, 1, -2, 9];
const output = input.slice().sort().reduceRight((acc, val, i) => {
return i % 2 === 0 ? [...acc, val] : [val, ...acc];
}, []);
console.log(output.join());
A slightly different approach is to sort the array ascending.
Get another array of the indices and sort the odds into the first half asending and the even values to the end descending with a inverted butterfly shuffle.
Then map the sorted array by taking the value of the sorted indices.
[-2, 0, 1, 2, 3, 3, 7, 9] // sorted array
[ 1, 3, 5, 7, 6, 4, 2, 0] // sorted indices
[ 0, 2, 3, 9, 7, 3, 1, -2] // rebuild sorted array
var array = [0, 3, 3, 2, 7, 1, -2, 9].sort((a, b) => a - b);
array = Array
.from(array, (_, i) => i)
.sort((a, b) => b % 2 - a % 2 || (a % 2 ? a - b : b - a))
.map(i => array[i]);
console.log(array);
This solution is not really elegant, but it does it's job.
const setOfNumbers = [0, 3, 3, 2, 7, 1, -2, 9];
const alternation = alternate();
const sortedSetNumbers = sortNormal(setOfNumbers);
function sortNormal(start) {
const result = [];
const interim = start.sort((a, b) => {
return b - a;
});
interim.map(n => {
if (alternation.next().value) {
result.splice(0, 0, n);
} else {
result.splice(result.length, 0, n);
}
});
return result;
}
function* alternate() {
let i = true;
while (true) {
yield i;
i = !i;
}
}
console.log(sortedSetNumbers);