This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 8 years ago.
Hi i need to remove the array from another array.Below is the code that i had tried
var dummyObj = ["item1"];
var dummyArray = [ "item1", "item3", "item2"];
var data1=removeFromArray(dummyArray, dummyObj);
console.log("data1"+data1)
function removeFromArray(array, item)
{
while((index = array.indexOf(item)) > -1)
array.splice(index,1);
return array
}
below is my output
item1,item3,item2
But the required output is
item3,item2
Dont know where i am going wrong.Any help regarding this will be much helpful
You argument item is an is an array object so you have to use it like item[0]
while((index = array.indexOf(item[0])) > -1)
if dummyObj contains for than one values then you have to add an extra loop
function removeFromArray(array, item)
{
for(var j=0;j<item.length;j++){
while((index = array.indexOf(item[j])) > -1)
array.splice(index,1);
}
return array
}
The problem with your code is that, item is actually dummyObj which is an array and that does not exist in dummyArray. That is why it fails to remove it.
You can use Array.prototype.filter, like this
dummyArray = dummyArray.filter(function(currentItem) {
return dummyObj.indexOf(currentItem) === -1;
});
console.log(dummyArray); // [ 'item3', 'item2' ]
Check out Underscore.js, a javascript utility belt:
http://underscorejs.org/#difference
You have few errors there:
while((index = array.indexOf(item)) > -1)
Should be
while((index = array.indexOf(item) > -1)
Also you need to loop through both dummyArray and dummyObj, because your item variable is actually dummyObj, so you need to loop through it to check each element separately.
Related
This question already has an answer here:
javascript filter multidimensional array
(1 answer)
Closed 1 year ago.
Im'm working on a JavaScript side prokect and I've got a json file with an array with arrays like this:
arr =
{
"values": [
["Form Factor", "OS"],
["Landscape", "Android 9\n(Source)"],
["Portrait", "Analogue OS"],
["Micro\nLandscape", "?"]
]
}
The first array with "Form factor" (index 0) are the headlines. If I want to get all the "form factors" from the arrays how would I do that?
I know that "Form Factor" has index 0 but how do i filter through several arrays at once with an index? in the end I want an array like
results = ["Form Factor", "Landscape", "Portrait", "Micro\nLandscape"]
I tried it like this:
const index = 0;
const result = this.arr.values.filter(function (eachElem) {
return eachElem == index;
});
But that just gives me back an empty array.
Don't forget to check this
arr.values.map(x => x[0])
Your code isn't working because a) index isn't defined, you need to also put it as a parameter and b) in your case no element will be true.
I would use a traditional for loop in your case but surely if you want you can do it with es6 magic.
let result = [];
for (let i = 0; i < arr.values.length; i++) {
result.push(arr.values[i][0]);
}
console.log(result);
Just use array.find() it's much easier and you can search for your element in your array:
const found = array1.find(element => element > 10);
This question already has answers here:
How to check if an array is a subset of another array in JavaScript?
(9 answers)
Closed 3 years ago.
So I have an array ["miranda","brad","johnny"] and I want to check if in the array the values are either equal to miranda or to john or even brad to return true one time and not three times if one or more of the names are present and if not It displays an error if any other value are in this array. Now to make my example clearer here is a snippet that would represent what I'm thinking of:
let array = ["miranda","brad","johnny"]
for(var i = 0; i < array.length;i++){
if(array[i] == "brad" || array[i] == "miranda" || array[i] == "john"){
console.log("success")
} else{
console.log("fail");
break;
}
}
Now my goal here is to simplify and shorten this code to be left with a one line condition, I have already tried this technique (Check variable equality against a list of values) with if(["brad","miranda","john"].indexOf(array) > -1) { // .. } but this does not solve my problem. Would you have any idea?
Thanks in advance.
You could use Array#every in combination with Array#includes.
var array = ["miranda", "brad", "johnny"],
needed = ["brad", "miranda", "john"];
console.log(array.every(s => needed.includes(s)));
let array = ["miranda","brad","johnny"]
array.forEach(item =>
console.log(["brad", "miranda", "john"].includes(item) ? "success" : "fail")
);
The answer above covers the solution but you just need to use Array#some instead of Array#every -
var array = ["miranda", "brad", "johnny"],
needed = ["brad", "miranda", "john"];
console.log(array.some(s => needed.includes(s)));
This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 6 years ago.
I have an array:
var a = [2,3,4,5,5,4]
I want to get unique array out of given array like
b = [2,3,4,5]
I have tried
a.filter(function(d){return b.indexOf(d)>-1})
and I don't want to use for loop.
You can simply do it in JavaScript, with the help of the second - index - parameter of the filter method:
var a = [2,3,4,5,5,4];
a.filter(function(value, index){ return a.indexOf(value) == index });
This is not an Angular related problem. It can be resolved in a couple of ways depending which libraries you are using.
If you are using jquery:
var uniqeElements = $.unique([2,3,4,5,5,4]);
The output would be:
[2,3,4,5]
If you are using underscore:
var uniqeElements = _.uniq([2,3,4,5,5,4]);
Same output.
And pure JS code:
var unique = [2,3,4,5,5,4].filter(function(elem, index, self) {
return index == self.indexOf(elem);
})
var b = a.filter( function( item, index, inputArray ) {
return inputArray.indexOf(item) == index;
});
This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 7 years ago.
I started with an array formatted like this:
var cus = {
"acct":[
{
"latitude":"41.4903",
"longitude":"-90.56956",
"part_no":"P1140",
"no_sold":1
},
{
"latitude":"48.118625",
"longitude":"-96.1793",
"part_no":"227",
"no_sold":1
},
....
]
Next I put all of the part_no in a separate array like this:
var list = [];
$.each(cus.acct,function(index,value){
list = [value["part_no"]];
These are the results when I do a console.log() of my array:
["P1140"]
["227"]
["224"]
["600"]
.....
["756"]
["756"]
["756"]
How do I remove duplicates from this array of just part_no's with javascript/jquery? I've looked at other examples but can't find one that works for me. Take note that I'm just beginning with javascript as well.
function getUnique(arr){
var result = [];
$.each(arr, function(i, e) {
if(typeof e != "undefined")
{
if ($.inArray(e, result) == -1) result.push(e)
}
});
return result;
}
If you can use any libraries like underscope or lodash will provide more options.
I would use the jQuery unique option. It should remove any duplicates from your array.
This question already has an answer here:
How to filter a javascript object array with variable parameters
(1 answer)
Closed 9 years ago.
I am looking for a way to filter my JavaScript Array() columns where the parentId is equal to a variable passed into the method.
// Array decleration
var columns = []; // Columns
//...
for (var i1 in columns) {
if (columns[i1].parentId == listItem) {
//...
Could anybody recommend the easiest way to filter this using either plain JavaScript or jQuery to avoid using the if statement as shown above?
var filteredColumns = columns.filter(function(column) {
return column.parentId == listItem;
});
array = [1,2,3,4,5];
result = $.grep(array, function(n,i) {
return n > 3;
});
This will return an array of filtered elements where the results are greater than 3. Here n is the element in consideration, and i the index of the element. So as per your requirement, the code can run like this:
resultArray = $.grep(columns,function(n,i) {
return n == parentId;
});
Use ES5 Array's filter method:
var filtered = columns.filter(function (item) {
return item.parentId === listItem
});
In the link above there is also a shim for old browsers.
You can also doing that manually:
var filtered = [];
for (var i = 0, item; item = columns[i++];)
if (item.parentId === listItem) filtered.push(item);
Don't use for…in to iterate over Array.