Filtering a JavaScript array [duplicate] - javascript

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.

Related

Sorting Array based on another array [duplicate]

This question already has an answer here:
javascript sorting array based on another array
(1 answer)
Closed 6 years ago.
I have an array that could be made up of any the following values:
input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];
'input' can be made of any # of these values, without any duplicates. I'm trying to figure out how to sort 'input' according to the order of 'sortingArray':
sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];
Any help would be greatly appreciated.
You can also use filter function and get copy of sortingArray including only values from input:
var input = ['S-1','S-2','S-3','S-4','S-5'];
var sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];
var result = sortingArray.filter((el)=>(input.indexOf(el) > -1));
console.log(JSON.stringify(result));
Build a look-up object from your "sorting array":
var indexes = sortingArray.reduce(function(lookup, key, index) {
lookup[key] = index;
return lookup;
}, {});
Now you can use that in a comparator function:
input.sort(function(k1, k2) {
return indexes[k1] - indexes[k2];
});
Simple use with for loop.And apply the if condition for half of the array length.Then pass with new array
var input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];
var c =eval(input.length/2);
arr=[];
for(var i=0; i<input.length; i++){
if(i < c)
{
arr.push(input[i]);
arr.push(input[i+c]);
}
}
console.log(arr)
You could use an object with the indices of the sorted array and sort the new array with it.
var input = ['S-1', 'S-2', 'S-3', 'S-4', 'S-5', 'S-6', 'S-7', 'S-8'],
sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"],
order = Object.create(null);
sortingArray.forEach(function (a, i) { order[a] = i; });
input.sort(function (a, b) { return order[a] - order[b]; });
console.log(input);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to get unique array with only filter in Javascript [duplicate]

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;
});

How to check for value in javascript object? [duplicate]

This question already has answers here:
How to get a key in a JavaScript object by its value?
(31 answers)
Closed 7 years ago.
I do have a javscript object containing a product name and the corresponding product code. The code is unique.
var products = {
"Pineapple":38,
"Apple":110,
"Pear":109
};
If i want to know the code for a product i can just do
var pineapplecode = products["Pineapple"];
How do I check if there is a product for a given number and if print it ? Or do I have to/should I change the way the data is saved ?
I think the shortest way would be:
var prodCode = 38;
var result = Object.keys(products)
.filter(function(k) { return products[k] == prodCode; })[0];
// result == "Pineapple"
See MDN
I guess you are basically asking if I can check the other way round, i.e. check for key by passing value.
Yes you can,
Either by iterating through all the key and values, check if the value is existing and finally return the key if the value exists
change the way you save the data, index it by product number rather than product name
here is the code to convert one form to another
var newProducts = {};
for( var prodName in products )
{
newProducts[ products[ prodName ] ] = prodName;
}
console.log( newProducts );
And here is the code to check a specific value
var valueToCheck = "110";
var prodNameToFind = "";
for( var prodName in products )
{
if ( products[ prodName ] == valueToCheck )
{
prodNameToFind = prodName;
}
}
console.log( prodNameToFind );
Just iterate over the keys and the properties values and break the iteration if found with Array.prototype.some()
The some() method tests whether some element in the array passes the test implemented by the provided function.
var products = {
Pineapple: 38,
Apple: 110,
Pear: 109
};
function getProduct(code) {
var product;
Object.keys(products).some(function (k) {
if (products[k] === code) {
product = k;
return true;
}
});
return product;
}
document.write(getProduct(109));

How to remove items from array who's got the same values [duplicate]

This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 7 years ago.
I am making some checking between array. It is in NodeJS.
The question is:
I have an array:
var items = [];
than I insert some values into it:
items[0] = {a:1, b:222};
items[1] = {a:1, b:333};
items[2] = {a:1, b:222};
items[3] = {a:1, b:4444};
items[4] = {a:1, b:222};
So, what I need to do is: to go threw all array and remove item's that has the same 'b' value.
Example:
After filtering, it should look like:
items[0] = {a:1, b:222};
items[1] = {a:1, b:333};
items[2] = {a:1, b:4444};
As you see elements with indexes 2 and 4 gone, because they has the same b value as element at index 0.
How can I write this little code in JavaScript?
You're looking for an Array.prototype.filter function:
var bValues = {};
items = items
.filter(function(item) {
return bValues[item.b] === undefined && (bValues[item.b] = true);
});
This works by checking if we have seen a particular bValue, and returning false if we have. If we haven't, we set that value on the bValues map and return true.
Edit: I like the nifty suggestion of #dandavis, using the this binding parameter to reduce variable names:
items = items
.filter(function(item) {
return this[item.b] === undefined && (this[item.b] = true);
}, {});
If I understand your question correctly, you want to do a pass to remove every single duplicate b value. This is actually more of an algorithm question than a Javascript question. There are lot of ways to do this, but my answer is going to focus on performance.
Here is one of the faster ways to do this in Javascript (O(n)):
var items = [];
// Insert a bunch of items with signature {a: Number, b: Number}
items = removeDuplicatesOfB(items);
function removeDuplicatesOfB(items) {
var map = {};
var filtered = [];
items.forEach(function (item) {
if (!map[item.b]) {
filtered.push(item);
map[item.b] = true;
}
});
return filtered;
}
At this point you could focus on abstracting out the duplicate removal to make this a reusable function.
All the answers propose roughly equivalent algorithms, so it boils down to what is most understandable. Here's one idea. We'll start off by describing the algorithm in English:
Of all the items, keep those with the first b.
For an item, "first b" means the index of this item is equal to the index of the first element whose b property is equal to the b property of the item.
Now we can pretty much transform that English into JavaScript.
function removeDuplicatesOfB(items) {
// Is this item the first in the array with its b property?
function firstB(item, idx) {
return idx // The index of this item
=== // equal to
items.findIndex( // the index of the first
e => // element
e.b // whose b property
=== // is equal to
item.b // the b property of the item.
)
;
}
return items . // Of all the items,
filter( // keep those with
firstB // the first b.
)
;
}
Or, in non-commented form:
function removeDuplicatesOfB(items) {
function firstB(item, idx) {
return idx === items.findIndex(e => e.b === item.b);
}
return items.filter(firstB);
}
Underscore
Underscore's _.uniq can do this in its sleep, by passing it a "predicate" telling it how to compare the objects for purposes of determining whether they are the "same":
_.uniq(items, function(item) { return item.b; })

which approach is best to search object in array?

I've sorted following ways to search for an object in array.
This question has been asked like countless times but I want to know which of the best from following ways. If there's another I'd like to know that too.
Using $.grep()
function is_in_array(arr,element){
var result = $.grep(arr, function(e){ return e.id == element; });
return result.length;
}
Above function returns length of array.
0 when element not present
1 when element present
length > 1 if more elements with same value present
using lookup object
var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
lookup[array[i].id] = array[i];
}
This way I don't need to traverse entire array each time. I'd just check for lookup[id] instead.
for loop in traditional way
function in_array(array, id) {
for(var i=0;i<array.length;i++) {
if(array[i].id === id) {
return true;
}
}
return false;
}
to check if element exists, i'd call in_array(arr,element).
Which approach is best ? Question seriously sounds duplicate and it is but I just want to make sure which is best from these three only.
Update
Array will contain objects like --
var arr = [];
var nameObj = {};
nameObj.label = "somename";
nameObj.id = 123;
arr.push(nameObj);
.
.
.
You could also use a combination of JSON (for comparison) and the Array.filter method:
var findvalue = JSON.stringify([somevalue]),
,found = [array].filter(
function(a){return JSON.stringify(a) === findvalue;}).length
;
// found > 0 means: findvalue found
A jsfiddle example
More about Array.filter and a shim for older browsers #MDN
You could use the built-in map() method instead of a loop:
var lookup=array.map(function(e){return e.id;});
(Not supported in IE 8)

Categories

Resources