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
Related
I'm learning Javascript and I'm wondering what the most elegant way to convert this: [1,8]
into this:[1,2,3,4,5,6,7,8]?
Thanks a lot!
const argarray = [1, 8]
const countToN = (array) => {
// init results array
let res = []
// start at the first value array[0] go *up to* the second array[1]
for (let i = array[0]; i <= array[1]; i++) {
res.push(i)
}
// return the result
return res
}
console.log(countToN([1, 10]))
This would accommodate what you're trying to do, but it's fairly brittle. You'd have to check that it's an array and that it has only 2 values. If you had other requirements, I could amend this to account for it.
Here's a solution without loops. Note that this only works with positive numbers. It supports arrays of any length, but will always base the result off of the first and last values.
const case1 = [1, 8];
const case2 = [5, 20];
const startToEnd = (array) => {
const last = array[array.length - 1];
const newArray = [...Array(last + 1).keys()];
return newArray.slice(array[0], last + 1);
};
console.log(startToEnd(case1));
console.log(startToEnd(case2));
Here's a solution that works for negative values as well:
const case1 = [-5, 30];
const case2 = [-20, -10];
const case3 = [9, 14];
const startToEndSolid = (array) => {
const length = array[array.length - 1] - array[0] + 1;
if (length < 0) throw new Error('Last value must be greater than the first value.');
return Array.from(Array(length)).map((_, i) => array[0] + i);
};
console.log(startToEndSolid(case1));
console.log(startToEndSolid(case2));
console.log(startToEndSolid(case3));
A simple for loop will do it. Here's an example that has error checking and allows you to range both backwards and forwards (ie [1, 8], and also [1, -8]).
function range(arr) {
// Check if the argument (if there is one) is
// an array, and if it's an array it has a length of
// of two. If not return an error message.
if (!Array.isArray(arr) || arr.length !== 2) {
return 'Not possible';
}
// Deconstruct the first and last elements
// from the array
const [ first, last ] = arr;
// Create a new array to capture the range
const out = [];
// If the last integer is greater than the first
// integer walk the loop forwards
if (last > first) {
for (let i = first; i <= last; i++) {
out.push(i);
}
// Otherwise walk the loop backwards
} else {
for (let i = first; i >= last; i--) {
out.push(i);
}
}
// Finally return the array
return out;
}
console.log(range([1, 8]));
console.log(range('18'));
console.log(range());
console.log(range([1]));
console.log(range([-3, 6]));
console.log(range([9, 16, 23]));
console.log(range([4, -4]));
console.log(range([1, -8, 12]));
console.log(range(null));
console.log(range(undefined));
console.log(range([4, 4]));
Additional documentation
Destructuring assignment
Use Array#map as follows:
const input = [1,8],
output = [...Array(input[1] - input[0] + 1)]
.map((_,i) => input[0] + i);
console.log( output );
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.
I want to perform an operation involving the current and the next array element.
For example, add current element with the next:
let arr = [0,1,2,3,4,5];
let newarr = arr.map((a,b) => a+b); //here, a and b are treated as the same element
expecting it to yield a new array of sums of current and next array element:
[0+1, 1+2, 2+3, 3+4, 4+5]
Is it possible to do that with map? If not, is there any other method that is suitable for manipulating multiple array elements in one operation?
here, a and b are treated as the same element
No. a is the value and b is the index. They happen to be the same in your particular data set.
Is it possible to do that with map?
Not with map itself. That will give you a new value for each value in the array, but you are starting with 6 values and ending up with 5, so you need an additional transformation.
Obviously you also need to use "the next value" instead of "the current index" too.
const arr = [0,1,2,3,4,5];
const newarr = arr.map((value, index, array) => value + array[index + 1]);
newarr.pop(); // Discard the last value (5 + undefined);
console.log(newarr);
You could slice the array and map with the value and value at same index of original array.
const
array = [0, 1, 2, 3, 4, 5],
result = array.slice(1).map((v, i) => array[i] + v);
console.log(result);
The second parameter in map is the index. Since map returns results for each iteration you can filter the unwanted item from the new array:
let arr = [0,1,2,3,4,5];
let newarr = arr.map((a,b) => a+arr[b+1]).filter(i => !isNaN(i));
console.log(newarr);
You can use reduce for that:
const arr = [0, 1, 2, 3, 4, 5];
const out = arr.reduce((acc, el, i) => {
if (i === arr.length - 1) { // don't do anything for the last element
return acc;
}
acc.push(el + arr[i + 1]);
return acc;
}, []);
console.log(out)
Using Array.prototype.slice(), Array.prototype.forEach().
const data = [0, 1, 2, 3, 4, 5],
numbers = data.slice(0, -1),
result = [];
numbers.forEach((number, index) => {
result.push(number + data[index + 1]);
});
console.log(result);
I have my array=[5,4,3,1] below, I want to .push(2), then .sort() my array and find out the new number's location in the array that I just pushed. I know the answer the new number's location is in array[1].
var array = [5,4,3,1];
array.push(2); //My new number
var sortedArray = arr.sort();
// sortedArray [1,2,3,4,5]
// The new number's position went to array[1]
Is there any method to find out which position my new number went to?
You could sort an array with indices and take the store index for serarching the inde fo the sorted array.
var array = [5, 4, 3, 1],
index = array.push(2) - 1,
indices = array
.map((_, i) => i)
.sort((a, b) => array[a] - array[b]);
console.log(index); // old index
console.log(indices.indexOf(index)); // new index
console.log(indices);
You can use findIndex.
const array = [5, 4, 3, 1];
const n = 32;
array.push(n);
const sortedArray = array.sort();
const index = sortedArray.findIndex(el => el === n);
console.log(sortedArray, index)
Note that you sort could be improved if you're using numbers and you want them to be in ascending order after the sort:
const sortedArray = array.sort((a, b) => b < a);
You can use reduce function.
This approach returns an array of indexes of number 2 if this is repeated.
In this case, will return an array with only one index.
Look at this code snippet
var array = [5,4,3,1];
array.push(2);
var indexes = array.sort().reduce((a, n, i) => {
if (n === 2) {
a.push(i);
}
return a;
}, []);
console.log(JSON.stringify(indexes));
See, returns an array with only one index.
Resource
Array.prototype.reduce()
I need to construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs.
The following solution works if in each array the numbers only repeat once, otherwise it breaks. Also, I don't know how to simplify and not use messy for loops:
function intersection(arrayOfArrays) {
let joinedArray = [];
let reducedArray = [];
for (let iOuter in arrayOfArrays) {
for (let iInner in arrayOfArrays[iOuter]) {
joinedArray.push(arrayOfArrays[iOuter][iInner]);
}
return joinedArray;
}
for (let i in joinedArray.sort()) {
if (joinedArray[i] === joinedArray[ i - (arrayOfArrays.length - 1)]) {
reducedArray.push(joinedArray[i]);
}
}
return reducedArray;
}
Try thhis:-
function a1(ar,ar1){
x = new Set(ar)
y = new Set(ar1)
var result = []
for (let i of x){
if (y.has(i)){
result.push(i)
}
}
if (result){return result}
else{ return 0}
}
var a= [3,4,5,6]
var b = [8,5,6,1]
console.log(a1(a,b)) //output=> [5,6]
Hopefully this snippet will be useful
var a = [2, 3, 9];
var b = [2, 8, 9, 4, 1];
var c = [3, 4, 5, 1, 2, 1, 9];
var d = [1, 2]
function intersect() {
// create an empty array to store any input array,All the comparasion
// will be done against this one
var initialArray = [];
// Convert all the arguments object to array
// there can be n number of supplied input array
// sorting the array by it's length. the shortest array
//will have at least all the elements
var x = Array.prototype.slice.call(arguments).sort(function(a, b) {
return a.length - b.length
});
initialArray = x[0];
// loop over remaining array
for (var i = 1; i < x.length; i++) {
var tempArray = x[i];
// now check if every element of the initial array is present
// in rest of the arrays
initialArray.forEach(function(item, index) {
// if there is some element which is present in intial arrat but not in current array
// remove that eleemnt.
//because intersection requires element to present in all arrays
if (x[i].indexOf(item) === -1) {
initialArray.splice(index, 1)
}
})
}
return initialArray;
}
console.log(intersect(a, b, c, d))
There is a nice way of doing it using reduce to intersect through your array of arrays and then filter to make remaining values unique.
function intersection(arrayOfArrays) {
return arrayOfArrays
.reduce((acc,array,index) => { // Intersect arrays
if (index === 0)
return array;
return array.filter((value) => acc.includes(value));
}, [])
.filter((value, index, self) => self.indexOf(value) === index) // Make values unique
;
}
You can iterate through each array and count the frequency of occurrence of the number in an object where the key is the number in the array and its property being the array of occurrence in an array. Using the generated object find out the lowest frequency of each number and check if its value is more than zero and add that number to the result.
function intersection(arrayOfArrays) {
const frequency = arrayOfArrays.reduce((r, a, i) => {
a.forEach(v => {
if(!(v in r))
r[v] = Array.from({length:arrayOfArrays.length}).fill(0);
r[v][i] = r[v][i] + 1;
});
return r;
}, {});
return Object.keys(frequency).reduce((r,k) => {
const minCount = Math.min(...frequency[k]);
if(minCount) {
r = r.concat(Array.from({length: minCount}).fill(+k));
}
return r;
}, []);
}
console.log(intersection([[2,3, 45, 45, 5],[4,5,45, 45, 45, 6,7], [3, 7, 5,45, 45, 45, 45,7]]))