Filtering arrays in JS [duplicate] - javascript

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

Related

position array elements in ascending order (numbers are found as substrings inside the array elements) [duplicate]

This question already has answers here:
Natural sort of alphanumerical strings in JavaScript
(6 answers)
Javascript sort on on part of string
(4 answers)
Closed 7 months ago.
I have an array, I want to position every array element in ascending order but the numbers are found as substrings of the array elements. I sketched the code below to give you an idea of what I am trying to achieve(it works but its ugly). What is the best way to position every element inside an array in ascending order when the numbers are found as substrings inside the array elements. Thanks in advance.
Take a look at my code to better understand my question!
//this works but is uglyyyyy
const myArray = ['test4.js', 'test3.js', 'test1.js', 'test2.js']
let tempArr = []
for (var i = 0; i < myArray.length; i++) {
tempArr.push(myArray[i].replace('test', '').replace('.js', ''))
}
const sortedTempArr = tempArr.sort()
let sortedArray = []
for (var i = 0; i < sortedTempArr.length; i++) {
for (var j = 0; j < myArray.length; j++) {
if (myArray[j].includes(sortedTempArr[i])) {
sortedArray.push(myArray[j])
}
}
}
console.log(sortedArray)
Yes that was ugly ;)
Sort takes a function
For descending, switch a and b
I am assuming only ONE number in the string. The regex will produce a wrong result if you have test2version1.js for example
//this works and is pretty
const myArray = ['test4.js', 'test3.js', 'test11.js', 'test1.js', 'test.js', 'test2.js'];
const re = /\D+/g; // anything not a number
const sortedArray = myArray
.slice(0) // shallow copy
.sort((a, b) => a.replace(re, "") - b.replace(re, ""));
console.log(sortedArray);
.sort() the .match(/\d+/)[0] number of each string (coerced into a number). The bracket notation ([0]) ensures that only the first match is used and everything else is ignored.
const array = ['test4.js','test11.js', 'test3.js', 'test1.js', 'test2.js'];
let result = array.sort((a, b) => +a.match(/\d+/)[0] - b.match(/\d+/)[0]);
console.log(result);

Convert array of items to key value [javascript] [duplicate]

This question already has an answer here:
JS : Convert Array of Strings to Array of Objects
(1 answer)
Closed 2 years ago.
My array is something like this:
languages: ["Afrikaans","Albanian","Arabic","Azerbaijani", "Bengali"...]
I want to convert it so that it looks like:
languages: [{id:0,"Afrikaans"},{id:1,"Albanian"},{id:2,"Arabic"},{id:3,"Azerbaijani"}, {id:4,"Bengali"},...]
Build an object in each iteration step and then return this obj to build the result array.
I have added a key for your languages because otherwise it isn't valid syntax.
let languages = ["Afrikaans","Albanian","Arabic","Azerbaijani", "Bengali"]
let res = languages.map((x, ind) => {
let obj = {
"id": ind,
"lang": x
}
return obj;
})
console.log(res);
A simple for loop does the trick here, and your final result is an array filled with incorrectly formatted objects so I took the liberty of adding the language property as you can see.
Let listOfLanguagesArray be your first array and finalArray be your result
var listOfLanguagesArray = ["Afrikaans","Albanian","Arabic","Azerbaijani", "Bengali"...];
var finalArray = [];
for (var j = 0; j < listOfLanguagesArray.length; j++) {
finalArray.push({
id: j,
language: listOfLanguagesArray[j]
});
}
It does seem that, however, what you're asking for is tedious and unnecessary work because you can traverse an array with more efficient methods than traversing an array of objects for the same information in the same order.

Applying filter option from an array [duplicate]

This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 2 years ago.
I am trying to apply filter option from an array.
options = [
"car",
"bike",
]
I have multiple filter select, that's why using an array to contain more then one option.
and let's say there is array that I want to filter.
array = [
"car",
"fruit",
"keyboard",
"computer"
]
if the option is string like options = "car" then the thing is very easy
if (!options.length) {
return array;
} else {
return array.filter(item => {
return item === options;
})
}
But the thing is how can I handle if the options is not string but an array?
For example I tried to put filter function inside for loop.
let len = options.length
console.log(len)
for (let i = 0; i < len; index++) {
return array.filter(item => {
return item === array[i];
})
}
but it didn't worked out. It's only taking first selected from an array.
You can try using Array.prototype.includes()
return options.includes(item);

map items of array to another array

I have an array:
arr = [ 1, 2 , 3 ]
And another array where i hold DOM elements as
Elem = [ 1, 3]
I need to iterate over arr and only do stuff if the index match. For example since I have elem 1 and 3 when I loop through arr something should only happen for 1 and 3 and 2 should be skipped since there is no elem 2.
Someone told me to look into associative arrays and I wonder how I can do this with the least number of lines.
I want the code to be simple and readable and so far all the examples of associative arrays make no sense and are bloated.
for(var i = 0;i<arr.length;i++){
if(Elem.indexOf(arr[i])>-1){
//Elem contains arr[i] (contains object that at index i in arr)
//will be called only for 1 and 3 in arr
arr[i] = ... //do what you want with this object.
}
}
Do you mean this?
I modified the second array a bit to allow defining multiple actions in one place. I am not sure if I understand you correctly.
// array of DOM objects available
var arr = ['object1-selector', 'object2-selector', 'object3-selector'];
// array of actions with items that the method should be applied to
var actions = [
{
items: ['object1-selector', 'object3-selector'],
perform: function(elem) {
alert(elem);
}
},
{
items: ['object2-selector'],
perform: function(elem) {
alert(elem);
}
},
{
items: ['object4-selector'],
perform: function(elem) {
alert(elem);
}
}
];
//forEach loop that iterates over actions and checks if selector exists.
//If yes - it invokes the method
actions.forEach(function(action) {
action.items.forEach(function(item) {
if(arr.indexOf(item) > -1) {
action.perform(item);
}
});
});
If you want to have actions defined in one place and objects in a multidimensional array - let me know. I will try to adjust the example. If you don't store selectors but whole DOM objects, just modify the items: array and loop, that checks if element exists.
Oh, and here is jsfiddle: http://jsfiddle.net/3WJxc/2/. jQuery used only for alert() to show you working example.
Not really sure how you identify the elements in the second array but this is my suggestion. Array with ids
var arr = [ "id_1", "id_2", "id_3" ]
var Elem = {
"id_1": html_element,
"id_2": html_element,
"id_3": html_element
}
Then all you need to do is
for( var i = 0; i < arr.length; i++ ) {
if( Elem[ arr[i] ] ) {
// do stuff
}
}

Select from array of objects based on property value in JavaScript [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 8 years ago.
I have JSON objects that have several properties such as an id and name. I store them in a JavaScript array and then based on a dropdownlist I want to retrieve the object from the JavaScript array based on its id.
Suppose an object has id and name, how do I select them from my array variable?
var ObjectsList = data;
var id = $("#DropDownList > option:selected").attr("value");
ObjectsList["id=" + id];
Since you already have jQuery, you could use $.grep:
Finds the elements of an array which satisfy a filter function. The original array is not affected.
So something like this:
var matches = $.grep(ObjectsList, function(e) { return e.id == id });
that will leave you with an array of matching entries from ObjectsList in the array matches. The above assumes that ObjectsList has a structure like this:
[
{ id: ... },
{ id: ... },
...
]
If you know that there is only one match or if you only want the first then you could do it this way:
for(var i = 0, m = null; i < ObjectsList.length; ++i) {
if(ObjectsList[i].id != wanted_id)
continue;
m = a[i];
break;
}
// m is now either null or the one you want
There are a lot of variations on the for loop approach and a lot of people will wag a finger at me because they think continue is a bad word; if you don't like continue then you could do it this way:
for(var i = 0, m = null; i < ObjectsList.length; ++i) {
if(ObjectsList[i].id == wanted_id) {
m = ObjectsList[i];
break;
}
}

Categories