Compare elements in array for similarity js [duplicate] - javascript

This question already has answers here:
Check if all values of array are equal
(33 answers)
Closed 6 years ago.
I have an array for example
var a = [1,4,6,1,1,1,1];
and I need to compare each element in array for similarity. If all of them are similar I need return true, if one or more of them are different it should return false
Will be glad to get the answer.

Here's one method to achieve it, by using Set.
var a = [1,1,1,1];
var b = [1,2,3,4,5,1,2,3];
function check(arr) {
console.log([...new Set(arr)].length == 1 ? true : false);
}
check(a);
check(b);

if they all need to be the same then you could just check to see if everything in the array is equal to the first element by using filter and length. The length of the array filtered by any element in the list should equal the original length.
const a = [1, 4, 1, 1, 1, 1, 1];
function similarity(arr) {
let firstItem = arr[0];
return arr.filter(elements => elements == firstItem).length != arr.length ? false : true;
}
console.log(similarity(a));

You can make use of the every Method.
From MDN
The every() method tests whether all elements in the array pass the
test implemented by the provided function.
var notsimilar= [1,4,6,1,1,1,1];
var similar= [2,2,2];
console.log(notsimilar.every((x,i,a) => a[i] === a[0]));
console.log(similar.every((x,i,a) => a[i] === a[0]));

Related

How utilize array.splice() method in if statement [duplicate]

This question already has answers here:
Looping through array and removing items, without breaking for loop
(17 answers)
Remove Strings, Keep Numbers In Array With JavaScript
(5 answers)
How to remove all the numbers from an array?
(4 answers)
Closed 3 months ago.
I am trying to iterate over an array of strings with a "mistake" element that needs to be spliced. How can I utilize the array.splice() method to remove that item, in this case a typeof "number" within an array of strings? The below code returns the original array with the 'number' still present.
var inputFunction = function filterOutNumbers(array) {
// iterate over input array
for (var i = 0; i < array.length; i++) {
// if type of current value is not equal to string, delete current value
if (typeof array[i] !== 'string') {
array.splice(array[i]);
}
}
return array;
}
var inputArray = ['only', 'words', 'go', 'in', 78, 'here']
var output = inputFunction(inputArray);
console.log(output); // should log ['only', 'words', 'go', 'in', 'here']
The easier way to go about it would be to use filter() to create a filtered copy of the array:
const array = ['only', 'words', 'go', 'in', 78, 'here'];
const result = array.filter(v => typeof v === 'string');
console.log(result);
If you insist on modifying the array in place with splice():
const array = ['only', 'words', 'go', 'in', 78, 'here'];
for (let i = array.length - 1; i >= 0; i--) {
if (typeof array[i] !== 'string') array.splice(i, 1);
}
console.log(array);
It's important here to iterate in reverse. If you iterate forward, the index values will no longer match once you splice the array, resulting in elements being skipped.
Also look at the documentation for splice(). The usage in your original code is incorrect.

Return array index except a specific index [duplicate]

This question already has answers here:
How to remove item from array by value? [duplicate]
(37 answers)
Closed 4 years ago.
array["Hi","I","Hate","Love","You"];
how can I return "Hi I Love You" and delete the index "Hate".
Can I do this using Slice? From what I know if I use slice such as below:
array.slice(2,3);
It will return only "Hate" instead of getting rid of it, which is what I want.
There is very similar function (language-wise) thats doing what you need
const array = ["Hi","I","Hate","Love","You"];
array.splice(2,1);
console.log(array);
With a little upgrade, you can ask your V8 about if someone likes you or not. Just say his/her name loud and click on Run code snippet. The first response is true, you cannot repeat it for the same person.
const array = ["Hi","I","Hate","Love","You"];
let i=0;
if (Math.random() > 0.5) {
i++;
}
array.splice(2+i,1);
console.log(array);
Try the splice method:
const a = [1, 2, 3, 4]
a.splice(1, 1); // idx, count
console.log(a);
var arr = ["Hi","I","Hate","Love","You"];
var newarr = Array.prototype.concat(arr.slice(0,2), arr.slice(3));
console.log(newarr);
_.remove from lodash library will do the job.
_.remove(array, function(item) {
return item ===“Hate”;
})
https://lodash.com/docs/#remove
You can use array filter method
var org = ["Hi", "I", "Hate", "Love", "You"];
let newArray = org.filter(function(item) {
return item !== 'Hate'
});
console.log(newArray)

Filtering arrays in JS [duplicate]

This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 4 years ago.
I can't seem to figure this out.
I have two arrays. One of the arrays contains all the IDs of the other array, plus more.
var arr1 = [1,2,3,4,5]
var arr2 = [3,5]
My first array contains a lot more information which my second array does not (many other keys). I need to find a way to select all the elements of the first array that are present in the second array and return them so that I have just the elements of arr2 but with all the additional data in arr1. How can I do this?
EDIT: I should make it clear that in the first array, I am looking for specific IDs that match the indexes of the second array. So the solutions here are really good but not quite what I'm after. Example:
[ 0: { id: 1, name: "fred" } ...]
I want to match the id with my second array, not the index. Hope this makes sense!
I implemented a set data structure few months back, this is the difference function
function difference (firstarr,secondarr) {
let diffSet = [];
for ( let i = 0; i < secondarr.length ; i++ ) {
let hasValue = secondarr.includes(firstarr[i]);
if ( ! hasValue ) {
diffSet.push(secondarr[i]);
}
}
for ( let i = 0; i < firstarr.length ; i++ ) {
let hasValue = secondarr.includes(firstarr[i]);
if ( ! hasValue ) {
diffSet.push(firstarr[i]);
}
}
return diffSet;
};
console.log(difference([1,2,3,4],[3,4]));
Use filter and includes of Array.protitype.
var arr1 = [1,2,3,4,5]
var arr2 = [3,5,7]
console.log(arr1.filter(x=>!arr2.includes(x)));
arr2.forEach(function(x){
if(!arr1.includes(x)){
arr1.push(x);
}
})
console.log(arr1);

check every element of an array [duplicate]

This question already has answers here:
Why is using "for...in" for array iteration a bad idea?
(28 answers)
Closed 4 years ago.
What is the most efficient way to check a certain condition on every element of an array and return false if one or more elements do not meet the condition, for example, I have this array for example
arr = ["foo","azeaze", "wazeazerar"]
for(var ar in arr){
if(ar.length > 5){
console.log(false)
}else{
console.log(true)
}
}
as you can see it return true even if the element "foo" length is not greater than 5
You can use Array.prototype.every() in a one line function
arr = ["foo","azeaze", "wazeazerar"]
const isittrue = currentval => currentval.length > 2
console.log(arr.every(isittrue));
arr = ["foo","azeaze", "wazeazerar"]
console.log(arr.every(elem => elem.length >= 5))

Using indexOf method on array, getting all indexes and not just first [duplicate]

This question already has answers here:
How to find the indexes of all occurrences of an element in array?
(16 answers)
Closed 8 years ago.
Say that I have an array containing strings:
var array = ["test","apple","orange","test","banana"];
and some strings are exactly the same (test). Say that I want to get all the indexes in the array where the string test is located in the array and not just the first indexOf. Is there a nice solution to this problem that is as fast as possible and not using jQuery, I.E getting 0,2 as a result?
Thanks
You can use the builtin Array.prototype.forEach like this
var indices = [];
array.forEach(function(currentItem, index) {
if (currentItem === "test") {
indices.push(index);
}
});
console.log(indices);
Even better you can use Array.prototype.reduce like this
var indices = array.reduce(function(result, currentItem, index) {
if (currentItem === "test") {
result.push(index);
}
return result;
}, []);
console.log(indices);
Since you want the solution to be even working in IE, you might want to go with the plain old loop, like this
var indices = [], i;
for (i = 0; i < array.length; i += 1) {
if (array[i] === "test") {
indices.push(i);
}
}
console.log(indices);

Categories