How to get only values with not duplicated from an array [duplicate] - javascript

This question already has answers here:
Javascript remove all occurrence of duplicate element, leaving the only one that is unique
(10 answers)
Closed 3 years ago.
Here is an array : [2,2,3,3,5,7,9,9]
from this array, i needs the values not it doesn't have an duplicate. how to get it?
const onlyUniqueWithoutDup = array.filter((item) => !item.indexOf(array))
looking the result as : [5,7];
any help?

You can use:
const array = [2,2,3,3,5,7,9,9];
const result = array.filter((item, index, arr) => (arr.lastIndexOf(item) == arr.indexOf(item)));
console.log(result);

Create an object where the keys will be the element from this array and then the value will the number of repetition. Then iterate this object and get the keys where value is only 1
let data = [2, 2, 3, 3, 5, 7, 9, 9];
let newData = data.reduce((acc, curr) => {
if (acc[curr]) {
acc[curr] += 1;
} else {
acc[curr] = 1
}
return acc;
}, {});
let nonDup = [];
for (let keys in newData) {
if (newData[keys] === 1) {
nonDup.push(keys)
}
}
console.log(nonDup)

Related

How to flatten a two dimensional array in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 days ago.
The community is reviewing whether to reopen this question as of 8 days ago.
Improve this question
This is an example. Values can be text, numbers, or more values.
var array = [[1,2],[ [3,4],[5,6] ],[1,2],[1,2]]
This is the result I want (Note [3,4],[5,6]).
var flattened = [[1,2],[3,4],[5,6],[1,2],[1,2]]
Use Array.flatMap() to iterate the array a flatten the 1st level of sub-arrays. Wrap in another array all elements that are 1 dimension deep.
const a = [[1,2],[[3,4],[3,4]],[1,2],[1,2]]
const result = a.flatMap(v =>
Array.isArray(v[0]) ? v : [v]
)
console.log(result)
Using reduce iterate the array. Combine the current element (v) with the accumulator (acc) by spreading (2 dimensions), or by add (1 dimension).
const a = [[1,2],[[3,4],[3,4]],[1,2],[1,2]]
const result = a.reduce((acc, v) =>
Array.isArray(v[0])
? [...acc, ...v] // 2d
: [...acc, v] // 1d
, [])
console.log(result)
You can flatten the array with a simple reduce (if you have only one level of nesting)
const result = aa.reduce((acc, cur) => {
if(Array.isArray(cur[0]))
return [...acc, ...cur];
return [...acc, cur];
}, []);
You can convert this like this:
function flatten(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
function groupByPairs(arr) {
let result = [];
for (let i = 0; i < arr.length; i += 2) {
result.push([arr[i], arr[i + 1]]);
}
return result;
}
let input = [[1,2],[[3,4],[3,4]],[1,2],[1,2]];
let flat = flatten(input);
let output = groupByPairs(flat);
console.log(output);
And this will give the output [[1, 2], [3, 4], [3, 4], [1, 2], [1, 2]]

Finding the lonely integer - JavaScript [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 8 months ago.
Consider the array [1,2,2]
The array contains two unique values: 1, 2
The array contains duplicate values: 2
The lonely integer is 1
How can the lonely integer be returned?
For an array where you only care about grabbing the first integer which is lonely, you can check if the indexOf and lastIndexOf are the same. If they are, then it's lonely.
const array = [2, 2, 1, 3, 4, 3, 4];
const findLonely = (arr) => {
for (const num of arr) {
if (arr.indexOf(num) === arr.lastIndexOf(num)) return num;
}
return 'No lonely integers.';
};
console.log(findLonely(array));
If you have an array that has multiple lonely values, you can use this method to find all of the lonely values:
const array = [2, 2, 1, 3, 4, 3, 4, 6, 8, 8, 9];
const findAllLonely = (arr) => {
const map = {};
arr.forEach((num) => {
// Keep track of the number of time each number appears in the array
if (!map[num]) return (map[num] = 1);
map[num]++;
});
// Filter through and only keep the values that have 1 instance
return Object.keys(map).filter((key) => {
return map[key] === 1;
});
};
console.log(findAllLonely(array)); // expect [1, 6, 9]
const array = [0,1,2,2,1,5,4,3,4,3,2];
let lonely = array.filter((item,index)=> array.indexOf(item) === array.lastIndexOf(item));
console.log(lonely);
Working Demo :
// Array with duplicates
const arrWithDuplicates = [1, 2, 2];
var result = arrWithDuplicates.sort().filter((x,i,arr) => x !== arr[i+1] && x !== arr[i-1]);
console.log(result); // [1]
For each element your can use .filter() to help count the how many times the element is repeated. Then use .filter() again to return only those elements that appear once.
const nums = [1,2,2,3,4,4,4,5,5,6,7,7,7,8,8];
const singles = nums.filter(
//count how many times each element appears
num => nums.filter(n => n === num)
//return only those with freq. of 1
.length === 1
);
console.log( singles );
//OUTPUT: [ 1, 3, 6 ]
Use a 'for' loop with the filter function to loop through the array and only return the value that appears once
const arr = [0, 1, 2, 2, 1];
let unique;
for(var i = 0; i < arr.length; i++) {
if(a.filter(x => x == arr[i]).length == 1) {
unique = arr[i]
}
}
return unique;
the code below solves the challenge with O(n) complexity
function lonelyinteger(a) {
let result;
a.every((e)=>{
if(a.filter(x=>x==e).length==1) {
result = e;
return false;
}return true;
})
return result;
}
O(n) complexity
function lonelyinteger(a) {
for (let i = 0; i < a.length; i++) {
const count = a.filter((v) => v === a[i]).length;
if (count === 1) {
console.log(a[i]);
return a[i];
}
}
}
If there is multiple unique number in an array = [1,2,3,4,5,3,2,1] here 4 and 5 both are unique ,there is two lonely integer so the output should be like this result = [4,5]. In case of single unique integer we can return the result as result = [3] or result = 3. The below code snippet will solve both the scenario.
const array = [1,2,3,4,5,3,2,1]
let result = []
array.every(e => {
if(array.filter(x => x == e).length == 1) {
result.push(e)
}
return true
})
console.log(result)
Explanation: step by step
Your desire array from where you need to get the lonely integer.
We defined result as an array.
You can use simple for loop or array forEach (learn about forEach).
We are using array filter method (learn about filter) to get our work done. Here array.filter(x => x == e) this will result when the value of e is 1 (first element of the array) then the output will be [1,1].
So for 1 the .length == 1 will return false. This process will continue to get false and the if condition will not get executed until a the 'e' became 4 (4th element of the main array).
When 'e' became 4 then the result of array.filter(x => x == 4) will be [4] so the condition array.filter(x => x == e).length == 1 will be true and the if condition will execute. And inside that we are pushing the value 4 to the result array. You can add a next line return false to stop the execution and you will get only one single lonely integer.
return true is required here only if you're using the every method (learn about array every method)
Play with the code to get better understanding or comment if you've some question about this solution. Please give a up-vote if this answer is helpful.

Exclude duplicates from array [duplicate]

This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Completely removing duplicate items from an array
(11 answers)
remove all elements that occur more than once from array [duplicate]
(5 answers)
Closed 2 years ago.
I am trying to exclude duplicate numbers from the array. For example: if I filter an array of [1,2,2,3,5,5] the output should be [1,3].
function unique(arr) {
let sortArr = arr.sort()
let res = []
for (let i = 0; i < arr.length; i++) {
if (sortArr[i] != sortArr[i + 1]) {
res.push(sortArr[i])
}
}
return res
}
console.log(unique([1, 2, 2, 3, 5, 5]))
I was trying not to add duplicate numbers into an array, but instead of [1,3] I am getting [1,2,3,5]
The easiest tweak would be to check that both the next element and the previous element don't equal the current element:
function unique(arr) {
let sortArr = arr.sort()
let res = []
for (let i = 0; i < arr.length; i++) {
if (sortArr[i] != sortArr[i + 1] && sortArr[i] !== sortArr[i - 1]) {
res.push(sortArr[i])
}
}
return res
}
console.log(unique([1, 2, 2, 3, 5, 5]))
But .sort has a computational complexity of O(n log n). This can be done in O(n) time by counting up the number of results in an object instead:
function unique(arr) {
const ones = new Set();
const dupes = new Set();
for (const item of arr) {
if (dupes.has(item)) continue;
if (ones.has(item)) {
dupes.add(item);
ones.delete(item);
} else ones.add(item);
}
return [...ones];
}
console.log(unique([1, 2, 2, 3, 5, 5]))
Using Array.reduce, you can get the duplicated count of each item and based on that data, can get the non-duplicated values only as follows.
function unique(arr) {
const groupBy = arr.reduce((acc, cur) => {
acc[cur] ? acc[cur] ++ : acc[cur] = 1;
return acc;
}, {});
return Object.entries(groupBy)
.filter(([key, value]) => value === 1)
.map(([key]) => +key);
}
console.log(unique([1, 2, 2, 3, 5, 5]));
Count the number of values and returns only those that are equal to 1
function unique(array) {
var map = new Map();
array.forEach(a => map.set(a, (map.get(a) || 0) + 1));
return array.filter(a => map.get(a) === 1);
}
console.log(unique([1, 2, 2, 3, 5, 5]));

How to check if array element is the only one of its value in array?

I've seen many similar questions and answers here but none that directly answered this question. For each array element I'm looking for a way (with JavaScript) to check if it's the only one of its kind in the array, or if there is at least one other of it. For example:
const arr = [1,2,2]
looking for something that will return
true, false, false
when looping through arr.
const arr = [1, 2, 2];
console.log(arr.map(item => arr.indexOf(item) === arr.lastIndexOf(item)));
const arr = [1, 2, 2];
arr.map(item => arr.indexOf(item) === arr.lastIndexOf(item));
You can do it in two passes:
build a Map containing the count of each element
look up each element in that Map
Like so:
const getCounts = iterable => {
const counts = new Map();
for (const x of iterable) {
counts.set(x, (counts.get(x) ?? 0) + 1); // use || for ES6 compat
}
return counts;
};
const arrCounts = getCounts(arr);
arr.map(x => arrCounts.get(x) === 1)

Find indices of all duplicate records in js

Suppose I have an array as below:
Arr1 = [12,30,30,60,11,12,30]
I need to find index of elements which are repeated in array e.g.
ans: 0,1,2,5,6
I've tried this code but it is considering just single element to check duplicates.
First get all the duplicates using filter() and then using reduce() get he indexes of only those elements of array which are in dups
const arr = [12,30,30,60,11,12,30];
const dups = arr.filter(x => arr.indexOf(x) !== arr.lastIndexOf(x));
const res = arr.reduce((ac, a, i) => {
if(dups.includes(a)){
ac.push(i)
}
return ac;
}, []);
console.log(res)
The time complexity of above algorithm is O(n^2). If you want O(n) you can use below way
const arr = [12,30,30,60,11,12,30];
const dups = arr.reduce((ac, a) => (ac[a] = (ac[a] || 0) + 1, ac), {})
const res = arr.reduce((ac, a, i) => {
if(dups[a] !== 1){
ac.push(i)
}
return ac;
}, []);
console.log(res)
You could use simple indexOf and the loop to get the duplicate indexes.
let arr = [12,30,30,60,11,12,30]
let duplicate = new Set();
for(let i = 0; i < arr.length; i++){
let index = arr.indexOf(arr[i], i + 1);
if(index != -1) {
duplicate.add(i);
duplicate.add(index);
}
}
console.log(Array.from(duplicate).sort().toString());
A slightly different approach with an object as closure for seen items which holds an array of index and the first array, in which later comes the index and a necessary flattening of the values.
This answer is based on the question how is it possible to insert a value into an already mapped value.
This is only possible by using an object reference which is saved at the moment where a value appears and which is not seen before.
Example of unfinished result
[
[0],
[1],
2,
[],
[],
5,
6
]
The final Array#flat removes the covering array and shows only the index, or nothing, if the array remains empty.
[0, 1, 2, 5, 6]
var array = [12, 30, 30, 60, 11, 12, 30],
indices = array
.map((o => (v, i) => {
if (o[v]) { // if is duplicate
o[v][1][0] = o[v][0]; // take the first index as well
return i; // return index
}
o[v] = [i, []]; // save index
return o[v][1]; // return empty array
})({}))
.flat() // remove [] and move values out of array
console.log(indices);
You could use Array#reduce method
loop the array with reduce.At the time find the index of argument
And check the arguments exist more than one in the array using Array#filter
Finaly push the index value to new accumulator array.If the index value already exist in accumalator.Then pass the currentIndex curInd of the array to accumulator
const arr = [12, 30, 30, 60, 11, 12, 30];
let res = arr.reduce((acc, b, curInd) => {
let ind = arr.indexOf(b);
if (arr.filter(k => k == b).length > 1) {
if (acc.indexOf(ind) > -1) {
acc.push(curInd)
} else {
acc.push(ind);
}
}
return acc;
}, []);
console.log(res)
Below code will be easiest way to find indexes of duplicate elements
var dupIndex = [];
$.each(Arr1, function(index, value){
if(Arr1.filter(a => a == value).length > 1){ dupIndex.push(index); }
});
This should work for you

Categories

Resources