is there an AngularJS way of checking if a value exists in an array
var array1 = ["a","b","c"]
i'm trying to do this..
var array2 = ["c", "d", "e"]
angular.forEach(array2, function (a) {
if (a /*is NOT in array1*/) {
array1.push(a);
} else {
return false
}
});
You can use Array.indexOf which will return -1 if it's not found or the index of the value in the array.
So in your case:
if (array2.indexOf(a) < 0) {
array1.push(a);
}
You just need to use native Array.prototype.indexOf to check if value is in array or not:
var array2 = ["c", "d", "e"]
angular.forEach(array2, function (a) {
if (array2.indexOf(a) === -1) {
// a is NOT in array1
array1.push(a);
}
});
https://www.w3schools.com/jsref/jsref_includes_array.asp
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");
Related
If I have an array like const fruits = ["apple", "orange", "banana", "apple", "grape", "apple"] how can I use indexOf() (or another function if one exists) to find the index of every match?
Put another way, fruits.indexOf("apple") will only return 0 right now, but I want way to return an array with every matching index: [0, 3, 5].
Answer from mdn , Read the Docs
const indices = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = array.indexOf(element);
while (idx !== -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]
Here, inside the while loop, the second argument of indexOf method will determine the starting pointing point for finding index.
And the loop is updating it for next occurrences and storing it in an indices array
You can use .reduce():
const apples = fruits.reduce((result, fruit, index) => {
if (fruit === "apple")
result.push(index);
return result;
}, []);
You could of course wrap that in a function so that you could pass an array and a value to look for, and return the result.
You could use a combination of Array#map and Array#filter methods as follows:
const
fruits = ["apple", "orange", "banana", "apple", "grape", "apple"],
matchFruit = fruit => fruits
.map((f,i) => f === fruit ? i : -1)
.filter(i => i > -1);
console.log( matchFruit( "apple" ) );
I'm trying to filter arr2. If the element doesn't have an ID listed in arr, then I want it to be removed. How could I make this happen in javascript?
var arr= ["a", "b", "d"]
var arr2=[{id:"a", value:1},{id:"b", value:2}, {id:"c", value:3}]
result:
[{id:"a", value:1},{id:"b", value:2}]
Thanks in advance :)
You can use reduce and in the callback function check if arr includes the id of the object under iteration. If so then add the elements in the accumulator array
var arr = ["a", "b", "d"]
var arr2 = [{
id: "a",
value: 1
}, {
id: "b",
value: 2
}, {
id: "c",
value: 3
}];
const newData = arr2.reduce((acc, curr) => {
if (arr.includes(curr.id)) {
acc.push(curr)
}
return acc;
}, []);
console.log(newData)
if arr items are always strings you can do this:
var arr = ["a", "b", "d"];
var arr2 = [{id:"a", value:1},{id:"b", value:2}, {id:"c", value:3}];
let str = arr.join('')
let filtered = arr2.filter(x => str.includes(x.id));
console.log(filtered)
this should do it
var arr= ["a", "b", "d"]
var arr2=[{id:"a", value:1},{id:"b", value:2}, {id:"c", value:3}]
const filteredArray = arr2.filter(obj => {
return arr.includes(obj.id)
})
Using filter, reduce, and includes are all nearly twice as slow as simply using a loop. To walk you through it, all it does is check over every element in the second array and check to see if it's id property is in the first array, and if it is, it clones it. Also, for future reference, that title is written poorly. A much better title would be "How to filter array of objects based on a list of possible ID properties"
var arr= ["a", "b", "d"]
var arr2=[{id:"a", value:1},{id:"b", value:2}, {id:"c", value:3}]
let clone = []
for(let i = 0;i < arr2.length;i++){
for(let j = 0;j < arr.length; j++) if(arr2[i].id === arr[j]) clone.push(arr2[j])
}
console.log(clone)
I've searched high and low for an answer to this, but nothing.
I have a nested array and want to find it by exact value but can't seem to get it to work:
let rowLetters = ["A","B","C",["D","E"],"F"];
for(n=0;n<rowLetters.length;n++){
if(rowLetters[n] === ["D","E"]){
console.log("Found");
}
console.log(rowLetters[n]);
}
Console Output:
"A"
"B"
"C"
["D","E"] // <-- There it is..
"F"
What am I doing wrong?
You need to check
if item is an array,
if item has the same length as the wanted value array and
if the values of the arrays are equal.
let rowLetters = ["A", "B", "C", ["D", "E"], "F"],
search = ["D", "E"];
for (const item of rowLetters) {
if (Array.isArray(item) && item.length === search.length && search.every((v, i) => item[i] === v)) {
console.log(item);
}
}
You can use filter with JSON.stringify()
let data = ["A", "B", "C", ["D", "E"], "F"];
let search = data.filter(ele => JSON.stringify(ele) == JSON.stringify(["D", "E"]));
if (search.length > 0) {
console.log("found")
}
Are you looking for something like find() mixed with Array.isArray()?
let rowLetters = ["A","B","C",["D","E"],"F"];
console.log(rowLetters.find(i => Array.isArray(i)))
You cannot compare an array to an array because you are comparing by a reference and not a value. You can however cast the value to a json string and compare, however, this requires exact order in both arrays.
let rowLetters = ["A","B","C",["D","E"],"F"];
for(let i of rowLetters){
if(JSON.stringify(i) === JSON.stringify(["D","E"])) {
console.log("Found");
}
}
You can use .find and JSON.stringify:
let rowLetters = ["A","B","C",["D","E"],"F"];
let arrayToFind = JSON.stringify(["D","E"])
let nestedArray = rowLetters.find( arr => JSON.stringify(arr) === arrayToFind );
console.log(nestedArray);
A better way to check if two arrays are equal would be using .every and .includes as follows:
let rowLetters = ["A","B","C",["D","E"],"F"];
const arraysAreEqual = (arr1, arr2) => {
if(arr1.length != arr2.length) return false;
return arr1.every( e => arr2.includes(e) );
}
const arrayToFind = ["D","E"];
let nestedArray = rowLetters.find( arr => arraysAreEqual(arr, arrayToFind) );
console.log(nestedArray);
I need to create a function that inputs a new value into an empty array, and then the value stays in the array, even if the value changes. Let me explain with an example and I have so far:
var arr = [];
arr.unshift("f");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("e");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("d");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("c");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("b");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("a");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
arr.unshift("z");
if (arr.length > 6) {
arr.pop();
}
console.log(arr);
Here in the empty array a new value gets inputted in first position and stays in the array arr. This is what I get in the console:
(6) ["f"]
(6) ["e", "f"]
(6) ["d", "e", "f"]
(6) ["c", "d", "e", "f"]
(6) ["b", "c", "d", "e", "f"]
(6) ["a", "b", "c", "d", "e", "f"]
(6) ["z", "a", "b", "c", "d", "e"]
which is exactly what I want to achieve. Instead of these values I need a var that will get updated regularly.
var newValue = value_to_be_updated;
function myFunction(newValue) {
var arr = [];
arr.unshift(newValue);
return arr
}
if (arr.length > 6) {
arr.pop();
}
My goal is to reduce the above code and make it a function, but couldn't find anything helpful. Also is there any way the value inputted stays in the array, even if removed from the var?
Any help will be hugely appreciated!!!!!
Thanks in advance
You should be getting the new value dynamically using for example a prompt, if you are expecting the value of arr to remain the same after changing the source code that would not work.
Still has #gurvinder372 said your function should look something like this
var arr = [];
function myFunction(newValue) {
arr.unshift(newValue);
if (arr.length > 6) {
arr.pop();
}
return arr
}
then to use it you can do something like this
for (var i = 0; i<8; i++){
var value = prompt('enter char');
myFunction(value);
}
If Array.prototype.filter returns an array, why can't I invoke push() on this return value immediately?
Example:
var arr = ["a", "ab", "c", "ad"];
var arr2 = arr.filter(function(elmnt) { return elmnt.indexOf("a") > -1; });
// result: ["a", "ab", "ad"]
arr2.push("aaa");
// result: ["a", "ab", "ad", "aaa"]
Ok so far.
But what about chaining that push() call to the filter() call?
var arr = ["a", "ab", "c", "ad"];
var arr2 = arr.filter(function(elmnt) { return elmnt.indexOf("a") > -1; }).push("aaa");
// result: 4
Why does chaining filter() and push() result in the number of elements that I would expect, rather than an array of those elements?
The problem is not with what filter() returns, instead it is with what push() returns.
push() returns the new length of the array, and not the array itself.
So when you do:
var arr2 = arr.filter(function(elmnt) { return elmnt.indexOf("a") > -1; }).push("aaa");
arr2 will be assigned the new length of the array (which happens to be 4 in your case), and not the new array as such.
A modified version that'll do what you want would be:
var arr = ["a", "ab", "c", "ad"], arr2;
(arr2 = arr.filter(function(elmnt) { return elmnt.indexOf("a") > -1; })).push("aaa");
// now arr2 is ["a", "ab", "ad", "aaa"]
I suggest you use concat();
var arr = ["a", "ab", "c", "ad"], arr2;
(arr2 = arr.filter(function(elmnt) { return elmnt.indexOf("a") > -1; })).concat("aaa");
// now arr2 is ["a", "ab", "ad", "aaa"]
now run the above code and see the result/error.
Analyze the difference between your answer before and after running the code
Q2. correct the code so that method chain starts working
function filterOddNumbers(num) {
if (num % 2 === 0) {
return true;
} else {
return false;
}
}
const evenNumbers = [1, 2, 3, 4, 5].push().filter(filterOddNumbers);