How to retrieve the value from an array without index - javascript

[["Django UnChainers","AA-24010"],["General","AA-26191"]]
I have one array in above form. I want to retrieve all the value with prefix AA (which are in the second position). Is there any way where I can fetch the value by passing prefix?.
I know the way where I can get the value by passing index but may be tomorrow index can get change so is it possible to fetch the value by passing prefix?

In case OP wants a function to do this.
function(arr, pattern){
return arr.map(function(x){
return x.filter( word => ~ word.indexOf(pattern))
});
}
var arr =
[ [ "Django UnChainers", "AA-24010" ], [ "General", "AA-26191" ]];
var list = arr.map(function(x){
if(~(x[1].indexOf('AA'))){
return x[1];
}
});
console.log(list);
In case the index changes in future, iterate through each string and check for the "AA" string. Check the below code.
var arr =
[ [ "Django UnChainers", "AA-24010" ], [ "General", "AA-26191" ]];
var list = arr.map(function(x){
return x.filter( word => ~ word.indexOf('AA'))
});
console.log(list);

this is shorter
var = [nested array]
a.filter(x => x[1].startsWith('AA'))
//in case you are not sure about the index
a.filter(x => x.filter(y => y.startsWith('AA').length > 0))

Related

Fill empty values of a nested array with specific value Javascript

I have a function called Action which receives an array parameter like this.
[
['X','','O'],
['O','','O'],
['X','X','']
]
I want this function to return an array like this where each empty section of the previous array is filled individually with a specific value, e.g Y.
[
[
['','Y',''],
['','',''],
['','','']
],
[
['','',''],
['','Y',''],
['','','']
],
[
['','',''],
['','',''],
['','','Y']
]
]
I know I can do that with forEach but it needs nested forEach which I think isn't very optimal. Is there any better way of doing that?
This should work:
let arr = [
['X','','O'],
['O','','O'],
['X','X','']
]
let res = []
arr.map((item, index)=>{
item.map((sub, indx) =>{
if(sub === ""){
let array_=
[
['','',''],
['','',''],
['','','']
];
array_[index][indx] = "Y";
res.push(array_)
}
})
})
console.log(res)
You could avoid nesting loops with the following steps
flatten the matrix into a 1-d array
get the indices of the empty sections
create new flatten 1-d arrays with empty indices from previous result marked as 'Y'
transform flatten 1-d arrays back to 3x3 matrix
const arr = [
["X", "", "O"],
["O", "", "O"],
["X", "X", ""],
]
const res = arr
.flat() // flatten the array
.map((section, i) => [section, i])
.filter(([section, _]) => section === "")
.map(([_, i]) => i) // get the indices of empty sections
.map(sectionIdx =>
Array.from({ length: 9 }, (_, i) => (i === sectionIdx ? "Y" : ""))
) // create new flattened array with empty indices marked as 'Y'
.map(flattenedArr => [
flattenedArr.slice(0, 3),
flattenedArr.slice(3, 6),
flattenedArr.slice(6, 9),
]) // turn back flatten array into 3x3 matrix
console.log(res)
I feel compelled to give the trivial answer, which is to continue using nested .forEach. This results in very readable code, which is, in my experience, more valuable than high performance code most of the time.
I'd begin by looping over each row and column of your input. Every time you encounter an matching cell (i.e. empty string, in your case), clone the input structure (using .map to '') and replace the matching element with the desired replacement string (e.g. 'Y').
const input = [
['X','','O'],
['O','','O'],
['X','X','']
]
const result = [];
input.forEach((row, iRow) => row.forEach((col, iCol) => {
if (col == '') {
const clone = input.map(row => row.map(col => ''));
clone[iRow][iCol] = 'Y';
result.push(clone);
}
}));
console.log(result);

Iterate nested array to get the same index value from all objects at the same time

I have a nested array like following:
[
myfield: {value1,value2},
myotherfield: {value1,value2}
]
If i have the next scenario
[
myfield: {"A","B"},
myotherfield: {"C","D"}
]
How can i iterate the arrays to get the value1 of both fields at the same time? In this case i need to get A & C on the first iteration and B & D on the second iteration.
const data = {
myfield: ["A","B"],
myotherfield: ["C","D"]
};
data.myfield.forEach((fieldA, index) => {
const fieldB = data.myotherfield[index];
console.log(fieldA, fieldB);
})
Note1: Use this if both entries have the same length.
Note2: If both entries can have a different length then you need to check what of the two has the highest length while making the other entries return null.
const data = A.map((data_A, index) => {
const data_B = B[index]
console.log("data", data_A, data_B )
})

get only the unique value of an array

I am new to javascript and I tried like using distinct but its not what im looking for
example array:
let arr = [ {key:"1",value:"dog"},
{key:"1",value:"dog"},
{key:"2",value:"cat"},
{key:"3",value:"bird"},
{key:"3",value:"bird"},
]
on the code I try is its just removing the duplicate like
[ {key:"1",value:"dog"},
{key:"2",value:"cat"},
{key:"3",value:"bird"}, ]
how can I get only the
[ {key:"2",value:"cat"} ]
what I mean is only the one who have no duplicate and its removing those array that have the exact same?
You can map your objects to stringified versions of your objects so you can then use .indexOf and .lastIndexOf() to compare if the object found appears in different locations in your array, if the last and first index appear in the same location then it can be said that they're the same object (ie: a duplicate doesn't exist) and can be kept in your resulting array like so:
const arr = [{key:"1",value:"dog"},{key:"1",value:"dog"},{key:"2",value:"cat"},{key:"3",value:"bird"},{key:"3",value:"bird"}];
const searchable = arr.map(JSON.stringify);
const res = arr.filter((obj, i) => {
const str = JSON.stringify(obj);
return searchable.indexOf(str) === searchable.lastIndexOf(str);
});
console.log(res);
If you can use Javascript libraries such as underscore or lodash, I recommend having a look at _.xorBy function in their libraries. From lodash:
_.xorBy([arrays], [iteratee=_.identity])
Basically, you pass in the array that in here is an object literal and you pass in the attribute that you want to all occurrences of remove duplicates with in the original data array, like this:
var data = [ {key:"1",value:"dog"}
, {key:"1",value:"dog"}
, {key:"2",value:"cat"}
, {key:"3",value:"bird"}
, {key:"3",value:"bird"}
];
var non_duplidated_data = _.xorBy(data, 'key');
Source - https://lodash.com/docs/4.17.14#xorBy
You can use reduce and Map
let arr = [{key:"1",value:"dog"},{key:"1",value:"dog"},{key:"2",value:"cat"},{key:"3",value:"bird"},{key:"3",value:"bird"}]
let mapper = arr.reduce( (op,inp) => {
let {key} = inp
op.set(key, op.get(key) || {value: inp, count:0})
op.get(key).count++
return op
},new Map())
let final = [...mapper.values()].reduce((op,{value,count}) => {
if(count === 1){
op.push(value)
}
return op
},[])
console.log(final)
Using the "find" method, you will get exactly what you are looking for "{key:"2",value:"cat"}".
arr.find((item, index) => {
const foundDup = arr.find((s, sIndex) => sIndex !== index && s.key === item.key);
return !foundDup;
});
If you don't mind using a library, I strongly suggest using the "ramda" library.
const arr = [ {key:"1",value:"dog"}
, {key:"1",value:"dog"}
, {key:"2",value:"cat"}
, {key:"3",value:"bird"}
, {key:"3",value:"bird"}
];
const result = R.uniq(arr);
result will be:
[{"key": "1", "value": "dog"}, {"key": "2", "value": "cat"}, {"key": "3", "value": "bird"}]
you can use "lodash" or other similar libraries too.

How to check if any of the strings from an array with variable length are present in another string?

I am trying to filter some data from an array in a JSON file, based on an input of the form string1, string1,string2, string1,string2,string3 etc., that is, some strings separated by a ,.
What I'm trying to do:
let arrInput = document.getElementById('inputBox').val.split(',');
for(let i = 0; i < arrToFilter.length; i++){
if(.........what to write here?...........){
arrOutput.push(arrToFilter[i]);
}
}
return arrOutput;
If the arrInput had a fixed length, I could accomplish this using indexOf != -1 for each element in arrInput, but here, since the length of arrInput is variable, how can I check if at least one of the strings present in arrInput is also present as a substring in arrToFIlter[i]?
Edit:
Example:
Let arrToFilter be ["abcqwer", "pizza", "definition", "abcdef", "example"]
Case 1 :
Say the input entered (in an <input> element) is abc,def.
For this, the arrOutput should be ["abcqwer", "definition", "abcdef"]
Case 2:
Say the input entered is abc
Expected output : ["abcqwer", "abcdef"]
Simple way is using some and filter,
var string = 'ad,kk,sb';
var array = ['adik', 'klop', 'pp'];
var stringers = string.split(',');
var result = array.filter((arr) => {
var isPresent = stringers.some(stringer => arr.includes(stringer));
return isPresent ? true : false;
});
console.log(result);
You need to iterate both arrays
let arrToFilter = ['abcqwer', 'pizza', 'definition', 'abcdef', 'example'];
let arrOutput = [];
let arrInput = document.getElementById('inputBox').value.split(',');
arrToFilter.forEach(filter => {
arrInput.forEach(input => {
if (!!input && filter.includes(input)) {
arrOutput.push(filter);
}
});
});
// distinct the output
return arrOutput.filter((v, i, a) => i === a.indexOf(v));

How to create an ordered array from values that have an order number?

So I have a series of strings, which contain and image path and order # concatenated.
They look like this:
const images = [
'photo1.jpg,0'
'photo2.jpg,2'
'photo3.jpg,1'
]
So the correct order should be: photo1, photo3, photo2.
What I need to do is process this into a correctly ordered array with just the path values. So ultimately I need:
const orderedImages = [
'photo1.jpg'
'photo3.jpg'
'photo2.jpg'
]
What is the best way to do this?
You can use array.sort to order them and array.map to remove order value.
const images = [
'photo1.jpg,0',
'photo2.jpg,2',
'photo3.jpg,1'
]
var output = images.sort(function(a,b){
return +a.split(',')[1] - +b.split(',')[1]
}).map(function(item){
return item.split(',')[0]
});
console.log(output)
You could split the values and assign to the given index.
var images = ['photo1.jpg,0', 'photo2.jpg,2', 'photo3.jpg,1'],
array = [];
images.forEach(function (a) {
var aa = a.split(',');
array[aa[1]] = aa[0];
});
console.log(array);
Use Lodash and simply write:
var orderedImages = _(images)
.sortBy(function(element) { return element.split[','][1] ; })
.map(function(element) { return element.split[','][0]; })
.value();
Try this approach
var images = [
'photo1.jpg,0',
'photo2.jpg,2',
'photo3.jpg,1'
];
images.sort(function(a,b){
return Number(a.split(",")[1]) - Number(b.split(",")[1])
});
var orderedImages = images.map(function(item){
return item.split(",")[0];
});
console.log(orderedImages);
First, sort the element with help of Array#sort and then update the elements using Array#map method.
var images = [
'photo1.jpg,0',
'photo2.jpg,2',
'photo3.jpg,1'
]
// sort the element
.sort(function(a, b) {
// split the element and calculate
// return value based on that
return a.split(',')[1] - b.split(',')[1];
// iterate and generate new array with updated value
}).map(function(v) {
// generate array elemnt by removing the number part
return v.split(',')[0]
})
console.log(images)
With ES6 arrow function
var images = [
'photo1.jpg,0',
'photo2.jpg,2',
'photo3.jpg,1'
].sort((a, b) => a.split(',')[1] - b.split(',')[1]).map(v => v.split(',')[0])
console.log(images)

Categories

Resources